简体   繁体   English

Java socket:如何防止java.net.BindException

[英]Java socket : how to prevent java.net.BindException

I have implemented a LAN game and test on same computer by : create a class, create a server and a client in different thread in this class and connect together. 我已经在同一台计算机上实现了局域网游戏和测试:创建一个类,在这个类的不同线程中创建一个服务器和一个客户端并连接在一起。

After I close two windows (client and server) and I do above step again : run java class, create a server and a client. 关闭两个窗口(客户端和服务器)后,我再次执行上述步骤:运行java类,创建服务器和客户端。 I always meet this error : java.net.BindException (because this port has been created before and hasn't closed yet). 我总是遇到这个错误: java.net.BindException (因为此端口之前已创建,尚未关闭)。

Every time I create server socket, in catch, I always put serverSocket.close() . 每次我创建服务器套接字时,在catch中,我总是把serverSocket.close() but that error still met with me. 但这个错误仍然遇到了我。 Please give me some ideas to prevent this. 请给我一些想法以防止这种情况发生。

@ : and if we know one port has been created, can we close it, and make new ones ? @:如果我们知道已经创建了一个端口,我们可以关闭它并创建新端口吗?

Thanks :) 谢谢 :)

您应该将serverSocket.close()放在finally块中,并且可能需要等待几秒钟才能再次尝试绑定到该地址。

Anything put in a catch block isn't run unless an Exception is caught. 除非捕获异常,否则不会运行任何放入catch块的内容。 Instead, put the close() call in a finally block to ensure it is always run. 相反,将close()调用放在finally块中以确保它始终运行。

After calling close() on channel could be not enough. 在通道上调用close()之后可能还不行。 See explanation here: http://hea-www.harvard.edu/~fine/Tech/addrinuse.html The TCP connection could stay in CLOSE-WAIT or TIME-WAIT state. 请参阅此处的说明: http//hea-www.harvard.edu/~fine/Tech/addrinuse.html TCP连接可以保持CLOSE-WAIT或TIME-WAIT状态。 You can play with reusing the address (SO_REUSEADDR), but it didn't work for me. 您可以重复使用地址(SO_REUSEADDR),但它对我不起作用。 The best is to wait exactly the timeout which is set for CLOSE-WAIT or TIME-WAIT on network level. 最好是等待在网络级别上为CLOSE-WAIT或TIME-WAIT设置的超时。

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

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