简体   繁体   English

Java:如何杀死服务器线程,以便再次运行服务器不会导致“地址已在使用”

[英]Java: How to kill Server thread so that running the Server again will not cause “Address already in use”

I wrote a Server and a Client with GUI to transfer text between them and they work well. 我用一个GUI编写了一个服务器和一个客户端来在它们之间传输文本,它们运行良好。 I searched Google "how to send files through a network" then I found this beautiful solution (see Andrey Kozhanov reply) . 我搜索谷歌“如何通过网络发送文件”然后我​​找到了这个美丽的解决方案(参见Andrey Kozhanov回复)。 I moved the server class in the link to my server package and the client class in the link to my client package to try and they work well. 我将链接中的服务器类移动到我的服务器包中,并将链接中的客户端类移动到我的客户端包中以尝试它们运行良好。 Now I can send instant text messages, and instant files. 现在我可以发送即时文本消息和即时文件。

I wrote every thing necessary to make communication work smoothly to meet users expectations. 我写了一切必要的东西,使沟通顺利进行,以满足用户的期望。

The problem is The problem occur at a specific scenario. 问题是在特定情况下出现问题。

The two servers have different port numbers; 两台服务器有不同的端口号; (mine for text and the one in the link for files) (我的文本和文件链接中的文本)
Stage 1 阶段1
1- the client request the server to send a file. 1-客户端请求服务器发送文件。
2- the server reply with ( Yes ) ( dialogue yes-no-options ). 2-服务器回复( )( 对话是 - 否 - 选项 )。
3- the client navigate the File Chooser's List. 3-客户端导航文件选择器的列表。
4- the client cancel the File Chooser (didn't send a file). 4-客户端取消文件选择器(未发送文件)。
5- the server informed about the client cancellation. 5-服务器通知客户端取消。
Stage 2 第2阶段
- again - 再次
1- the client request the server to send a file. 1-客户端请求服务器发送文件。
2- the server reply with ( Yes ). 2-服务器回复( )。 error occur at the server side; 服务器端出错 ;

the first line of the error is: 错误的第一行是:

java.net.BindException: Address already in use: JVM_Bind java.net.BindException:已在使用的地址:JVM_Bind

I begin the receiving thread at the Server package like this 我在这样的服务器包中开始接收线程

        recieverThread = new Recieving();
        recieverThread.setDaemon(true);
        recieverThread.start();

The problem traced back to stage 1 number 5 (5- the server informed about the client cancellation.). 问题追溯到第1阶段第5 阶段 (5-服务器通知客户端取消。)。 since the server thread for receiving files from client start, then at point 5 I must stop it. 因为用于从客户端接收文件的服务器线程启动,所以在第5点我必须停止它。 to stop this thread I use combination of 停止这个线程我使用组合

        recieverThread.interrupt();
        recieverThread = null;

But when it started again at stage 2 , it seems that it still running and is not stopped. 但是当它在第2阶段再次启动时,它似乎仍在运行并且没有停止。 I want to kill it so that when I want to start a new thread no error occur. 我想要杀死它,以便当我想启动一个新线程时不会发生错误。

That is not a threading problem, but a server socket problem. 这不是线程问题,而是服务器套接字问题。 Reusing a Socket immediately is disallowed by TCP/IP because the reuser could see packets targeted at the old user. TCP / IP不允许立即重新使用套接字,因为重新使用者可以看到针对旧用户的数据包。

See this question on how to reuse sockets. 请参阅有关如何重用套接字的此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM