【问题标题】:Send and Receive large amount of data through tcp stream using read/write (Error)使用读/写通过 tcp 流发送和接收大量数据(错误)
【发布时间】:2015-09-25 20:56:58
【问题描述】:

我正在尝试通过 tcp 连接在我的服务器上接收任意长度的数据。首先,我的客户端通过 stream.write 将数据长度发送到服务器,然后发送实际数据。 在客户端,我收到长度并循环,直到成功接收到整个数据。

问题是:“无论数据长度如何,我在服务器上收到的大小都是 0”。我试图找出问题所在,但无法找到问题所在。任何形式的帮助/提示将不胜感激。

服务器端代码:

byte[] lengthOfData = new byte[2048];
byte[] buffer;
try
{
    stream = client.GetStream();
    eventLog1.WriteEntry("Size of 1st = "+stream.Read(lengthOfData,0,lengthOfData.Length));
    int numBytesToRead = ByteArraySerializer.BytesArrayToInt(lengthOfData);
    eventLog1.WriteEntry("number of bytes to read= "+numBytesToRead);
    buffer = new byte[numBytesToRead+10];
    int numBytesRead = 0;
    do
    {
        int n = stream.Read(buffer, numBytesRead, 10);
        numBytesRead += n;
        numBytesToRead -= n;
        eventLog1.WriteEntry("number of bytes read= " + numBytesRead);
    } while (numBytesToRead > 0);
 }
 catch (Exception e)     // Called automatically when Client Diposes or disconnects unexpectedly
 {
     eventLog1.WriteEntry("Connection Closes: "+e.ToString());
     lock (connectedClients)
     {
         connectedClients.Remove(client);
     }
     client.Close();

     break;
  }

客户端代码

byte[] command = ByteArraySerializer.Serialize<Command>(cmd);
byte[] sizeOfData = ByteArraySerializer.IntToBytesArray(command.Length);
stream.Write(sizeOfData, 0, sizeOfData.Length);
Console.WriteLine("Size of Data = "+command.Length);
stream.Write(command, 0, command.Length);

【问题讨论】:

    标签: c# sockets tcp stream network-programming


    【解决方案1】:

    在服务器上更改以下行

    byte[] lengthOfData = new byte[2048];
    

    byte[] lengthOfData = new byte[sizeof(int)];
    

    问题是服务器上的读取应该只读取 4 个字节的整数,而它也在读取其他数据,这些数据是在写入数据长度后写入的。如果我们想要获取数据的长度(整数),我们应该只读取 4 个字节。

    【讨论】:

      猜你喜欢
      • 2012-03-10
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2014-07-25
      • 2014-08-20
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多