C# 如何使用TcpClient避免死锁?

C# 如何使用TcpClient避免死锁?,c#,networking,tcpclient,tcplistener,C#,Networking,Tcpclient,Tcplistener,我目前正在尝试制作一个小服务器,但我遇到了一个问题,我相信是死锁。我的问题是如何避免C#Tcp中的死锁问题?让我给你看看 public static void SendString (TcpClient klient, string message) { byte[] byteBuffer = Encoding.UTF8.GetBytes(message); NetworkStream netStream = klient.GetStream();

我目前正在尝试制作一个小服务器,但我遇到了一个问题,我相信是死锁。我的问题是如何避免C#Tcp中的死锁问题?让我给你看看

        public static void SendString (TcpClient klient, string message) {
        byte[] byteBuffer = Encoding.UTF8.GetBytes(message);
        NetworkStream netStream = klient.GetStream();
        netStream.Write(byteBuffer, 0, byteBuffer.Length);
        netStream.Write(new byte[] { separator }, 0, sizeof(byte));
        netStream.Flush();
    }

    public static string AcceptString (TcpClient klient) {
        List<int> buffer = new List<int>();
        NetworkStream stream = klient.GetStream();
        int readByte;
        while ((readByte = stream.ReadByte()) != 0)
            buffer.Add(readByte);

        return Encoding.UTF8.GetString(buffer.Select<int, byte>(b => (byte)b).ToArray(), 0, buffer.Count);
    }
publicstaticvoidsendstring(TcpClient-klient,字符串消息){
byte[]byteBuffer=Encoding.UTF8.GetBytes(消息);
NetworkStream netStream=klient.GetStream();
Write(byteBuffer,0,byteBuffer.Length);
Write(新字节[]{separator},0,sizeof(字节));
netStream.Flush();
}
公共静态字符串AcceptString(TcpClient klient){
列表缓冲区=新列表();
NetworkStream=klient.GetStream();
int读取字节;
而((readByte=stream.readByte())!=0)
Add(readByte);
返回Encoding.UTF8.GetString(buffer.Select(b=>(byte)b.ToArray(),0,buffer.Count);
}

当双方都试图调用
SendString()
(对方)时是否会发生死锁?如果不是,到底是什么导致了僵局?我的意思是,我知道什么是僵局(当双方都在等待另一方的行动时),但它在C#networking中实际意味着什么

您的案例中没有死锁。至少我什么也看不见。为什么要有一个呢?

每台计算机都可以向另一台计算机发送任意数量的数据。数据将存储在目标计算机的网络接收缓冲区中,直到某个软件获取数据。通常,数据发送不受其他数据接收的影响。

死锁是死锁。这在所有语言中都是一样的。这不是死锁,而是无效的通信协议。当双方通信时,形成、终止消息的方式以及消息的确切序列称为协议。为了找到一个不会导致此类问题的有效协议,请研究一些现有的协议,如HTTP,以获得这个想法。你怎么会这样认为?AcceptString将永远不会与此特定代码一起返回,因为发件人从未关闭连接。这不是僵局,谢谢!我认为这是死锁,因为我的服务器只接受第一个字符串,而忽略了其他字符串。