?
class="java">import java.net.*; import java.io.*; import java.lang.*; public class Server extends Thread{ private ServerSocket serverSocket; public static void main(String[] args) { int port = Integer.parseInt(args[0]); try { Thread t = new Server(port); t.run(); } catch (Exception e) { e.printStackTrace(); } } public Server(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() + ", 连接结束..."); server.close(); } catch (SocketTimeoutException se) { System.out.println("连接超时..."); break; } catch (IOException ie) { ie.printStackTrace(); break; } } } }
?
import java.net.*; import java.io.*; import java.lang.*; public class Client { 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.getRemoteSocketAddress()); OutputStream outServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outServer); 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(); } } }
?