繁体   English   中英

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

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

我正在尝试将文件从客户端发送到服务器,因此我将文件加载到客户端的字节数组中,并通过 send() 方法将其发送到服务器,但接收到的数组不同且更大比发送的数组,我想知道这是否是协议问题(但我使用的是 tcp 协议来确保错误检测):

客户端代码:

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."; 

服务器代码:

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...";

您已经定义clientData = new byte[1024 * 5000]; - 然后你不要使用receivedBytesLen 我不记得Receive重载是否会在 EOF 之前读取尽可能多的内容,或者只是“一些或 EOF”(后者是Stream.Read行为),但您必须验证并使用receivedBytesLen

IMO,固定缓冲区的方法本质上是有缺陷的,因为它也不能很好地处理过大的输入。 我个人会在这里使用NetworkStream 那么你的整个代码变成:

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

这里另一种常见的方法是将预期大小作为数据的前缀发送; 这样您就可以验证您是否拥有所需的数据。 我个人不会使用此信息在 memory 中创建正确大小的缓冲区,因为这仍然不允许使用史诗大小的文件(但是, Stream可以)。

暂无
暂无

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

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