简体   繁体   中英

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. I searched Google "how to send files through a network" then I found this beautiful solution (see Andrey Kozhanov reply) . 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- the client request the server to send a file.
2- the server reply with ( Yes ) ( dialogue yes-no-options ).
3- the client navigate the File Chooser's List.
4- the client cancel the File Chooser (didn't send a file).
5- the server informed about the client cancellation.
Stage 2
- again
1- the client request the server to send a file.
2- the server reply with ( Yes ). error occur at the server side;

the first line of the error is:

java.net.BindException: Address already in use: 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.). since the server thread for receiving files from client start, then at point 5 I must stop it. 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. 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.

See this question on how to reuse sockets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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