Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java套接字的问题_Java_Sockets - Fatal编程技术网

java套接字的问题

java套接字的问题,java,sockets,Java,Sockets,在java中,我可以编写如下代码: ServerSocket ss = new ServerSocket(1111); Socket s = ss.accept(); // here s.getLocalPort() is 1111 ss.close(); // here this is ok even s is still connected with a client. ss = new ServerSocket(s.getLocalPort()); 在客户端: Socket

在java中,我可以编写如下代码:

 ServerSocket ss = new ServerSocket(1111);
 Socket s = ss.accept();
 // here s.getLocalPort() is 1111
 ss.close();
 // here this is ok even s is still connected with a client.
 ss = new ServerSocket(s.getLocalPort());
在客户端:

Socket s = new Socket("localhost", 1111);
// this line will throw an exception. 
ServerSocket ss = new ServerSocket(s.getLocalPort());

我不明白的是,上面两段代码的最后一行似乎没有区别,为什么它的工作方式不同?非常感谢您提供的任何信息。第一种情况下您关闭了套接字,第二种情况下您没有关闭,因此端口仍然被占用。

感谢您的快速回复,在第一种情况下,我刚刚关闭了服务器套接字“ss”,但套接字“s”仍然有效正确,但是,您不再侦听此端口的新连接,只与已建立的连接通信。是的,这是我的问题,请参见第二种情况,端口s.getLocalPort()上没有套接字侦听,但为什么我不能在其上创建套接字侦听?