简体   繁体   English

接收到的数据与通过 c 尖锐套接字发送的数据不同

[英]data received different from data sent through a c sharp socket

I'm trying to send a file from a client to a server, so I load the file in a byte array in the client side, and send it to the server through the send() method, but the received array is different and bigger than the array sent, I wonder if it's a protocol problem (but I'm using tcp protocol wich assure error detection ):我正在尝试将文件从客户端发送到服务器,因此我将文件加载到客户端的字节数组中,并通过 send() 方法将其发送到服务器,但接收到的数组不同且更大比发送的数组,我想知道这是否是协议问题(但我使用的是 tcp 协议来确保错误检测):

Client code:客户端代码:

IPAddress ipAddress = new IPAddress(ip);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

FileStream fl = File.Open("pos.xls",FileMode.Open);
byte[] fileData = ReadFully(fl);
fl.Close();  

byte[] clientData = new byte[ fileData.Length];
fileData.CopyTo(clientData,0);

curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);

curMsg = "File sending...";
clientSock.Send(clientData);

curMsg = "Disconnecting...";
clientSock.Close();
curMsg = "File transferred."; 

Server code:服务器代码:

curMsg = "Starting...";
sock.Listen(100);

curMsg = "Running and waiting to receive file.";
byte[] clientData = new byte[1024 * 5000];
while (true)
{
    Socket clientSock = sock.Accept();

    clientData = new byte[1024 * 5000];

    int receivedBytesLen = clientSock.Receive(clientData);
    curMsg = "Receiving data...";

    FileStream fz = writeFully(clientData);
    fz.Close();
    curMsg = "Saving file...";

You have defined clientData = new byte[1024 * 5000];您已经定义clientData = new byte[1024 * 5000]; - and you then don't use receivedBytesLen . - 然后你不要使用receivedBytesLen I can't remember whether that Receive overload will read as much as it can until EOF , or simply "some or EOF" (the latter being the Stream.Read behavior), but you must verify and use receivedBytesLen .我不记得Receive重载是否会在 EOF 之前读取尽可能多的内容,或者只是“一些或 EOF”(后者是Stream.Read行为),但您必须验证并使用receivedBytesLen

IMO, the approach of a fixed buffer is inherently flawed, as it doesn't cope well with oversized inputs either. IMO,固定缓冲区的方法本质上是有缺陷的,因为它也不能很好地处理过大的输入。 Personally I would use a NetworkStream here;我个人会在这里使用NetworkStream then your entire code becomes:那么你的整个代码变成:

using(var fz = File.Create(path)) {
    networkStream.CopyTo(fz);
}

Another common approach here is to send the expected size as a prefix to the data;这里另一种常见的方法是将预期大小作为数据的前缀发送; that way you can verify that you have the data you need.这样您就可以验证您是否拥有所需的数据。 I personally wouldn't use this information to create a correct-sized buffer in memory though, as that still doesn't allow for epic-sized files (a Stream , however, does).我个人不会使用此信息在 memory 中创建正确大小的缓冲区,因为这仍然不允许使用史诗大小的文件(但是, Stream可以)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM