问题
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