我写过简单的客户端(使用SocketChannel):
User friend = database.getUserByName("jonh");
SocketChannel friendSkt = SocketChannel.open(new InetSocketAddress(InetAddress.getByName(friend.getHost()), friend.getPort()));
System.out.println("Local: " + friendSkt.socket().getLocalSocketAddress()
+ " |Remote: "+ friendSkt.socket().getRemoteSocketAddress());
和服务器(使用简单的Socket):
ServerSocket skt = new ServerSocket(0);
Socket server = skt.accept();
InputStream x = server.getInputStream();
System.out.println("Local: " + server.getLocalSocketAddress() + " |Remote: "+ server.getRemoteSocketAddress());
即使connect没有返回异常而客户端写入socket(简单的getOutputStream.write(...)),服务器也不会读取并返回-1。所以我打印了每个插座的地址,发现了这个:
客户:Local: /192.168.0.2:58981 |Remote: /192.168.0.2:58968
服务器:Local: /192.168.0.2:58968 |Remote: /192.168.0.2:58980
客户端本地端口是服务器远程端口+ 1而不是相同的值是正常的吗?