我只是想知道C#中套接字的以下行为。 通常,TCP负责运输,包括在请求时终止连接。 所以我不明白,为什么这个示例代码有这些结果 我期望如果s2关闭到s3的连接,s3将无法发送更多数据。但是s3.send(...) - 调用没有产生任何错误(如下所示) 此外,我希望server / client-role对此行为没有影响,因为关闭套接字应该发送FIN并返回FIN / ACK,因此两个套接字都应该知道已关闭的连接。
所以请看一下这个示例代码:
void MyMethod()
{
IPAddress localIP = IPAddress.Loopback;
Socket s1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket s2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s1.Bind(new IPEndPoint(localIP, 20003));
s1.Listen(1);
s2.Bind(new IPEndPoint(localIP, 20004));
s2.ConnectAsync(new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(localIP, 20003) });
Socket s3 = s1.Accept();
Console.WriteLine($"Accepted Connection: {s3.LocalEndPoint} -> {s3.RemoteEndPoint}");
s1.Close();
Console.WriteLine($"S2: Connected: {s2.Connected} @ {s2.LocalEndPoint} -> {s2.RemoteEndPoint}");
Console.WriteLine($"S3: Connected: {s3.Connected} @ {s3.LocalEndPoint} -> {s3.RemoteEndPoint}");
s2.Shutdown(SocketShutdown.Both);
s2.Close();
SocketError error;
s3.Send(new byte[] {1, 2, 3}, 0, 3, SocketFlags.None, out error);
Console.WriteLine($"Transmission SocketError: {error}");
Console.WriteLine($"S2: Connected: {s2.Connected}");
Console.WriteLine($"S3: Connected: {s3.Connected} @ {s3.LocalEndPoint} -> {s3.RemoteEndPoint}");
s3.Close();
}
此代码生成此输出:
Accepted Connection: 127.0.0.1:20003 -> 127.0.0.1:20004
S2: Connected: True @ 127.0.0.1:20004 -> 127.0.0.1:20003
S3: Connected: True @ 127.0.0.1:20003 -> 127.0.0.1:20004
Transmission SocketError: Success
S2: Connected: False
S3: Connected: True @ 127.0.0.1:20003 -> 127.0.0.1:20004