开发者

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开发者_Python百科 than the array sent, I wonder if it's a protocol problem (but I'm using tcp protocol wich assure error detection ):

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]; - and you then don't use 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.

IMO, the approach of a fixed buffer is inherently flawed, as it doesn't cope well with oversized inputs either. Personally I would use a NetworkStream here; 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜