Simple Socket Example
原文網址:http://www.blogjava.net/zJun/archive/2007/07/24/76720.html
1.服务端
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Socket服务端程序
*
* @author zJun
*
*/
public class Server {
private ServerSocket server;
private DataOutputStream output;
private Socket socket;
public Server() {
try {
// 在端口5000建立服务
server = new ServerSocket( 5000 );
System.out.println( " 服务创建. " );
System.out.println( " 等待客户端连接 " );
socket = server.accept();
System.out.println( " 客户端已连接.\n关闭! " );
output = new DataOutputStream(socket.getOutputStream());
output.writeUTF( " 欢迎你.再见! " );
output.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
System.exit( 1 );
}
}
public static void main(String args[]) {
Server game = new Server();
}
}
2.客户端
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private Socket client;
private DataInputStream input;
public Client(String server, int port) {
try {
// 连接服务
if (server.equals( " localhost " )) {
client = new Socket(InetAddress.getLocalHost(), port);
} else {
client = new Socket(InetAddress.getByName(server), port);
}
// 从服务器读取信息
input = new DataInputStream(client.getInputStream());
String info = input.readUTF();
System.out.println(info);
// 关闭连接
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client( " localhost " , 5000 );
}
}
在取代localhost為ip的時候發生了一件糗事
就放了之後一直出現java.net.UnknownHostException
結果發現去掉ip前後的空格
也是就是從" xxx.xxx.xxx.xxx "改成"xxx.xxx.xxx.xxx"就OK了...
沒有留言:
張貼留言