Hi @亮亮 孙 , Welcome to Microsoft Q&A,
The exception is thrown due to connection timeout, not socket timeout. In a WAN environment, connections are typically more restricted, so the default connection timeout may be shorter than in a LAN environment.
You can set the connection timeout in client code to extend the duration of the connection. In the C# Socket class, you can achieve this by setting the timeout of the Socket.Connect method. Here's how to modify the client code to set a connection timeout:
public static void main(String[] parameters)
{
Socket client_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdress = IPAddress.Parse("your_server_wan_ip");
IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 9998);
//Set the connection timeout to 10 minutes (600000 milliseconds)
client_socket.ConnectTimeout = 600000;
try
{
client_socket.Connect(ipEndpoint);
}
catch (before SocketException)
{
// Handle connection exception
Console.WriteLine("Connection failed: " + ex.Message);
return;
}
// Code after successful connection
And (true)
{
String rl = Console.ReadLine();
client_socket.Send(Encoding.UTF8.GetBytes(rl.ToUpper()));
Bytes[] buffer = new Bytes[1024 * 1024];
int num = client_socket.Receive(buffer);
String str = Encoding.UTF8.GetString(buffer, 0, num);
Console.WriteLine(DateTime.Now.ToString() + ":"+"data : " + str);
}
}
You can extend the connection timeout by setting the ConnectTimeout property. Note that the timeout is in milliseconds.
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.