如何正确关闭套接字然后重新打开? [英] How to correctly close a socket and then reopen it?
问题描述
我正在为我所在的课程开发一款游戏,它完成了大约99%。但是,我意识到存在一个问题:如果服务器和客户端断开连接,并且客户端尝试重新连接(并且服务器已备份且运行正常),则客户端不会建立新连接。
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.
服务器和客户端都是多线程的。如果我向客户端发送 Kick
消息,那么客户端将关闭其套接字。如果我重新连接,我得到一个 SocketException
:套接字关闭,即使每次按下连接时,都会构造一个新的客户端,这基本上只是一个创建套接字并连接到的类带有get / send线程的服务器。
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.
你觉得我有什么不合逻辑吗?它就像它试图使用构造的旧Socket和Client,但如果我做了一些 println
调用,我可以看到它确实构造了一个新的它们和它们在不同的记忆位置。
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.
谢谢!
推荐答案
关闭后套接字,您不能重复使用它来共享服务器和客户端类之间的其他数据。从 Java Socket API ,关于 close()
方法的描述:
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:
I / O操作中当前阻塞的任何线程在这个套接字上将
抛出一个SocketException。
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.
关闭此套接字也将关闭套接字的InputStream和
OutputStream。
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.
这篇关于如何正确关闭套接字然后重新打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!