Sending and receiving custom objects using Tcpclient class in C#

后端 未结 3 740
孤独总比滥情好
孤独总比滥情好 2021-02-01 09:52

I have a client server application in which the server and the client need to send and receive objects of a custom class over the network. I am using TcpClient class for transmi

3条回答
  •  独厮守ぢ
    2021-02-01 10:20

    When receiving on client side you do not know how much data you want to read. You are only relying on the ReceiveBufferSize, while your data can be larger or smaller then that.

    I think the best approach here is to send 4 bytes that tells your client about the length of incoming data:

    byte[] userDataLen = BitConverter.GetBytes((Int32)userDataBytes.Length);
    netStream.Write(userDataLen, 0, 4);
    netStream.Write(userDataBytes, 0, userDataBytes.Length);
    

    and on the recieving end you first read the data length and then read exact amount of data.

    byte[] readMsgLen = new byte[4];
    readNetStream.Read(readMsgLen, 0, 4);
    
    int dataLen = BitConverter.ToInt32(readMsgLen);
    byte[] readMsgData = new byte[dataLen];
    readNetStream.Read(readMsgData, 0, dataLen);
    

    Infact, I just realized, that you might has to do a little more to assure you read all data (just an idea because I haven't tried it, but just incase you run into problem again you can try this).

    The NetworkStream.Read() method returns a number indicating the amount of data it has read. It might be possible that the incoming data is larger then the RecieveBuffer. In that case you have to loop until you read all of the data. You have to do something like this:

    SafeRead(byte[] userData, int len)
    {
        int dataRead = 0;
        do
        {       
            dataRead += readNetStream.Read(readMsgData, dataRead, len - dataRead);
    
        } while(dataRead < len);
    }
    

提交回复
热议问题