TcpClient 不接收所有数据

TcpClient doesn't reveive all data

我有一个像这样工作的“信使”应用程序: 客户端向服务器发送消息 -> 服务器将消息转发给其余客户端 -> 客户端读取消息。

服务器总是收到消息,但客户端不会。

将消息转发给所有客户端的代码(Server/TcpListener):

public static void SendToAll(TcpClient sender, string message)
{
   // Log the recieved message in the console
   Console.WriteLine(message);

   // Save the recieved message for new clients
   messageLog += message + "\n";

   byte[] msg = Encoding.ASCII.GetBytes(message);
   foreach (TcpClient client in clients.Keys)
   {
      if (client == sender || clients[client] == "") continue;
      if (!client.Connected)
      {
         clients.Remove(client);
         continue;

      }

      NetworkStream stream = client.GetStream();
      stream.Write(msg, 0, msg.Length);
   }
}

从服务器 (TcpClient) 读取消息的代码:

byte[] buffer = new byte[1024];
while (true)
{
   using (MemoryStream memoryStream = new MemoryStream())
   {
      Int32 bytes = 0;
      do
      {
         bytes = stream.Read(buffer, 0, buffer.Length);
         memoryStream.Write(buffer, 0, bytes);
      }
      while (stream.DataAvailable);
      Console.WriteLine(Encoding.ASCII.GetString(memoryStream.ToArray()));
}

Server (image attached)

Client1 (image attached)

Client2 (image attached)

找到答案。

问题可能是因为TCP速度慢;尚未完全读取所有流并已负责读取新数据。

所以我换了

byte[] buffer = new byte[1024];
while (true)
{
   using (MemoryStream memoryStream = new MemoryStream())
   {
      Int32 bytes = 0;
      do
      {
         bytes = stream.Read(buffer, 0, buffer.Length);
         memoryStream.Write(buffer, 0, bytes);
      }
      while (stream.DataAvailable);
      Console.WriteLine(Encoding.ASCII.GetString(memoryStream.ToArray()));
}

// ... Main() {
while (true) StartRead();
// ... }

public static async void StartRead(NetworkStream stream)
{
    byte[] buffer = new byte[1024];
    Int32 bytesRead = await stream.ReadAsync(buffer.AsMemory(0, buffer.Length));
    string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
    Console.WriteLine(message);         
}