gpt4 book ai didi

C# Socket.Connected 属性在调用 Socket.Receive 后更改为 false

转载 作者:太空狗 更新时间:2023-10-30 01:12:10 25 4
gpt4 key购买 nike

int readCount;
byte[] buffer = new byte[128];
SocketError socketError;

TcpClient tcpClient = tcpListener.AcceptTcpClient();
tcpClient.Client.ReceiveTimeout = 500; // #1
// tcpClient.Client.Connected is **true** here.
readCount = tcpClient.Client.Receive(buffer, 0, buffer.Length, SocketFlags.None, out socketError); // reacCount > 0
// tcpClient.Client.Connected is **false** here.

如果 #1 替换为 tcpClient.Client.Blocking = false;,则 tcpClient.Client.Connected 具有正确的值(true)。


我已将 Socket.ReceiveTime 属性设置为 100 并调用了 Socket.Receive()Receive() 返回了大于零的整数值。没有发生异常。在我使用复制的缓冲区完成工作后——我没有使用任何与 Socket 相关的方法——Socket.Connected 属性已更改为 false。为什么?

最佳答案

关键可能在什么TcpClient.Connected确实如此:

The Connected property gets the connection state of the Client socket as of the last I/O operation. When it returns false, the Client socket was either never connected, or is no longer connected.

Because the Connected property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns true. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions.

因此,当您没有阻塞并检查 Connected 值时,读取可能尚未完成,因此 Connected 仍为旧值。

关于C# Socket.Connected 属性在调用 Socket.Receive 后更改为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1011031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com