Socket socket=new Socket("localhost",9999); System.out.println("远程主机地址:"+socket.getRemoteSocketAddress()); DataOutputStream out=new DataOutputStream(socket.getOutputStream()); out.writeUTF("我是客户端,我要连你了,我来自:"+socket.getLocalSocketAddress()); DataInputStream input=new DataInputStream(socket.getInputStream()); System.out.println(input.readUTF()); socket.close();
public class Main extends Thread { private ServerSocket serverSocket; public Main(int port) throws IOException { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(10000);//超时时间,accept获取请求的超时时间,超过十秒就断Accept timed out } @Override public void run() { while (true) { System.out.println("等待远程 连接端口:" + serverSocket.getLocalPort()); try { Socket socket = serverSocket.accept();//SocketTimeoutException: Accept timed out System.out.println("远程主机地址:" + socket.getRemoteSocketAddress()); DataInputStream ds = new DataInputStream(socket.getInputStream()); System.out.println(ds.readUTF()); DataOutputStream out=new DataOutputStream(socket.getOutputStream()); out.writeUTF("你连接上我了:"+socket.getLocalSocketAddress()+" goodbye"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
这段代码,服务端加了多线程,新开了一个线程连接客户端。
也可以客户端多开几个线程请求服务端,就不写了。