Socket timeout not working

白昼怎懂夜的黑 提交于 2019-12-13 15:06:36

问题


I have a TCP Socket running on a C# machine. I need to connect that server socket from Android via Server IP and port as below:

InetAddress serverAddr = InetAddress.getByName(serverIp);
Socket socket = new Socket(serverAddr, serverPort);
socket.setSoTimeout(10*1000);

If c# machine doesn't have socket running on Android it hangs on:

Socket socket = new Socket(serverAddr, serverPort);

I need to implement 5 seconds as timeout like if it doesn't find server socket on this ip it could simply timeout.

Thoughts please..


回答1:


May this help you:

Create the socket with the no parameters constructor like this:

Socket socket = new Socket();

Then use

socket.connect(remoteAddress, timeout);

Another Way:

Socket socket= new Socket();   
socket.connect(new InetSocketAddress(hostip,port_num),connection_time_out); 



回答2:


InetAddress serverAddr = InetAddress.getByName(serverIp);
Socket socket = new Socket();
socket.connect(serverAddr, timeout);


来源:https://stackoverflow.com/questions/20780904/socket-timeout-not-working

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