//客户端程序
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class GreetingClient {
public static void main(String[] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try{
System.out.println(“链接到主机:”+serverName+”端口号:”+port);
Socket client = new Socket(serverName,port);
System.out.println(“远程主机地址:”+client.getLocalSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(“Hello from” + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println(“服务器响应:” + in.readUTF());
client.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
//服务器程序
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class GreetingServer extends Thread{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
while(true){
try{
System.out.println(“等待远程连接端口号:”+ serverSocket.getLocalPort()+”…”);
Socket server = serverSocket.accept();
System.out.println(“远程主机地址”+server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF(“谢谢你连接我”+server.getLocalSocketAddress()+”\nGoodbye!”);
server.close();
}
catch(SocketTimeoutException s){
System.out.println(“Socket time out”);
break;
}
catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
try{
Thread t = new GreetingServer(port);
t.run();
}
catch(IOException e){
e.printStackTrace();
}
}
}
$ javac GreetingServer.java
$ java GreetingServer 6066
$ javac GreetingClient.java
$ java GreetingClientlocalhost 6066
连接到主机:localhost ,端口号:6066
远程主机地址:localhost/127.0.0.1:6066
服务器响应: 谢谢连接我:/127.0.0.1:6066
Goodbye!