C# 使用读/写通过tcp流发送和接收大量数据(错误)
我试图通过tcp连接在我的服务器上接收任意长度的数据。首先,我的客户端通过stream.write向服务器发送数据长度,然后发送实际数据。 在客户端,我接收长度和循环,直到成功接收整个数据 问题是:“无论数据的长度是多少,我在服务器上收到的大小都是0”。我试图找出问题所在,但无法找到问题所在。任何形式的帮助/提示都将不胜感激 服务器端代码:C# 使用读/写通过tcp流发送和接收大量数据(错误),c#,sockets,tcp,stream,network-programming,C#,Sockets,Tcp,Stream,Network Programming,我试图通过tcp连接在我的服务器上接收任意长度的数据。首先,我的客户端通过stream.write向服务器发送数据长度,然后发送实际数据。 在客户端,我接收长度和循环,直到成功接收整个数据 问题是:“无论数据的长度是多少,我在服务器上收到的大小都是0”。我试图找出问题所在,但无法找到问题所在。任何形式的帮助/提示都将不胜感激 服务器端代码: byte[] lengthOfData = new byte[2048]; byte[] buffer; try { stream = client
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);
byte[]命令=ByteArraySerializer.Serialize(cmd);
字节[]sizeOfData=ByteArraySerializer.IntToBytesArray(command.Length);
stream.Write(sizeOfData,0,sizeOfData.Length);
Console.WriteLine(“数据大小=“+command.Length”);
stream.Write(command,0,command.Length);
更改服务器上的以下行
byte[] lengthOfData = new byte[2048];
到
问题是,服务器上的read应该只读取4字节的整数,而它也在读取其他数据,这些数据是在写入数据长度之后写入的。如果我们想得到数据的长度(整数),我们应该只读取4个字节
byte[] lengthOfData = new byte[sizeof(int)];