套接字超时不起作用

3
我有一个运行在C#机器上的TCP套接字。我需要通过以下服务器IP和端口从Android连接到该服务器套接字:
InetAddress serverAddr = InetAddress.getByName(serverIp);
Socket socket = new Socket(serverAddr, serverPort);
socket.setSoTimeout(10*1000);

如果 c# 机器在 Android 上没有运行套接字,它会停止响应:
Socket socket = new Socket(serverAddr, serverPort);

我需要将5秒钟作为超时时间实现,如果在这个IP上没有找到服务器套接字,它可以简单地超时。

请提供您的想法。

2个回答

7

希望这可以帮到你:

使用无参数构造函数创建套接字,如下所示:

Socket socket = new Socket();

然后使用

socket.connect(remoteAddress, timeout);

另一种方法:

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

Socket socket = new Socket(); socket.connect(new InetSocketAddress(hostip, port_num), connection_time_out); 对我来说完美无缺。谢谢 Bhavin。 - Tahir Jilani

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

java.net.Socket没有包含这样的构造函数:new Socket(serverAddr, serverPort, timeout)。需要进一步帮助吗? - Tahir Jilani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接