Java: how to stop a server (close a Socket) without an exception?

强颜欢笑 提交于 2019-12-06 03:01:36

I added START/STOP button which should start/stop server. But the code does not work like I want: connection isn't closed

That's because you're closing the ServerSocket, not an accepted socket.

and code goes to the IOException "THIS IS PROBLEM" (in ServerLogic part).

That's normal. Nothing wrong here.

Additionally clients still can contact with server.

Existing clients can continue to use their existing connections. If you want to close those, see next. No new connections can be created.

How to properly close connection without any exceptions?

Shut them down for input. That will cause the reads to incur an end of stream, which should already cause the threads concerned to close the socket and exit.

Should I just before closing the Socket send to all clients some message with demand of closeure or just closing the Socket on the server should be enough?

Closing the socket is sufficient. Sending an extra message doesn't add any value. The clients will get the usual end-of-stream indications from their reads, or an IOException: connection reset on their writes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!