地址已在使用 linux,Java Linux:java.net.BindException:地址已在使用中

I am using Linux Mint 14 KDE. I've successfully created Java tcp server and client, server IP:port is 10.10.1.10:9900 and my client IP:port 10.10.1.10:9901. When i connect my client for the first time everything is OK. The client connects and sends some data and disconnects. When i try connecting the client with the server right after disconnecting i get the next Exception.

我正在使用Linux Mint 14 KDE。我已經成功創建了Java tcp服務器和客戶端,服務器IP:端口是10.10.1.10:9900,我的客戶端IP:端口10.10.1.10:9901。當我第一次連接我的客戶端時一切正常。客戶端連接並發送一些數據並斷開連接。當我嘗試在斷開連接后立即將客戶端與服務器連接時,我得到下一個異常。

java.net.BindException: Address already in use

If i wait more than 1 minute everything is OK. On other forums i read that after closing the socket there is a tcp time_wait that is 60 seconds (1 minute). After changing it to 0 everything worked (If someone want to change it just add this line net.ipv4.tcp_fin_timeout=0 in /etc/sysctl.conf and execute this line in your terminal as root service networking restart). The next day i tried to do one more test and i got the same exception. I checked if the time is still 0 (U can check it with writing this in command line cat /proc/sys/net/ipv4/tcp_fin_timeout as root) and it was 0. I still had to wait 1 minute before reconnecting the client.

如果我等待超過1分鍾,一切都會好的。在其他論壇上,我讀到關閉套接字后,有一個60秒(1分鍾)的tcp time_wait。將其更改為0后,一切正常(如果有人想要更改它,只需在/etc/sysctl.conf中添加此行net.ipv4.tcp_fin_timeout = 0並在終端中執行此行作為root service networking restart)。第二天,我試圖再做一次測試,我得到了同樣的例外。我檢查時間是否仍為0(你可以在命令行cat / proc / sys / net / ipv4 / tcp_fin_timeout中以root身份寫這個來檢查它)它是0.我仍然需要等待1分鍾再重新連接客戶端。

Can someone help me how to configure that way so i don't get this exception. Waiting 1 minute is too much for real-time application. I know i can do this with letting the OS dynamically assign port number that is free, but that is not what my application needs are.

有人可以幫助我如何配置,所以我沒有得到這個例外。等待1分鍾對於實時應用來說太多了。我知道我可以通過讓操作系統動態分配免費的端口號來實現這一點,但這不是我的應用程序所需要的。

2 个解决方案

#1

1

After creating your client socket, but before binding it or connecting to the remote server, you should call Socket.setReuseAddress(true) to enable reusing the client port.

創建客戶端套接字后,但在綁定它或連接到遠程服務器之前,應調用Socket.setReuseAddress(true)以啟用重用客戶端端口。

#2

0

Don't specify a fixed client port, use zero. That way you will get a fresh one every time, or until you run out, which means you should be doing connection pooling at the client.

不要指定固定的客戶端端口,使用零。這樣你每次都會得到一個新的,或者直到你用完為止,這意味着你應該在客戶端進行連接池。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值