Sending and receiving custom objects using Tcpclient class in C#

后端 未结 3 781
孤独总比滥情好
孤独总比滥情好 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:16

    TCP is stream-based protocol (as opposed to datagram protocol) so it's possible to receive only part of sended data via Read method call.

    To solve this problem you may use DataLength field (as cornerback84 suggested) or you may use your own "application-level packet" structure.

    For example, you may use something like this

    |-------------------------------|
    |Begin|DataLength|   Data   |End|
    | 4b  |   4b     | 1..MaxLen|4b |
    |-------------------------------|
    

    where Begin - start packet identifier (for example 0x0A, 0x0B, 0x0C, 0x0D) DataLength - Data field length (for example, from 0 to MaxLength) Data - actual data (serialized Person class or some other data) End - end packet identifier (for example 0x01, 0x05, 0x07, 0x0F).

    That is, on client side you would wait not only for incoming data, after receiving data you would search you Application level packets, and you may deserialized Data part only after receiving valid packet.

提交回复
热议问题