java中如何关闭套接字,如何正确关闭套接字然后重新打开?

I'm developing a game for a class that I am in, and it is about 99% done. However, I realized there is a problem: If the server and client disconnect, and the client attempts to reconnect (and the server is back up and running fine), the client is not making a new connection.

The server and client are both multi-threaded. If I send the client a Kick message, what happens is the client will close its socket. If I reconnect, I get a SocketException: socket closed even though whenever connect is pressed, a new Client is constructed, which is basically just a class that creates a socket and connects to the server with a get/send thread.

Do you think there is anything I am doing illogically? It is like it is attempting to use the old Socket and Client that were constructed, but if I do some println calls, I can see that it does construct a new one and they are in different memory locations.

Thanks!

解决方案

After closing a socket, you cannot reuse it to share other data between Server and Client classes. From the Java Socket API, about close() method's description:

Any thread currently blocked in an I/O operation upon this socket will

throw a SocketException.

Once a socket has been closed, it is not available for further

networking use (i.e. can't be reconnected or rebound). A new socket

needs to be created.

Closing this socket will also close the socket's InputStream and

OutputStream.

If this socket has an associated channel then the channel is closed

as well.

Then, it isn't possible to close a socket and reopen it. That's the reason, I think, of the exception being thrown.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值