TCP is stream based, you get a stream of data from a client to server. You need to "deserialize" what you're expecting from the stream, if you can't build an application protocol that ensures each message sent is separately (which usually isn't a wise idea anyway with TCP).
So, you need to send with each message something that allows you to differentiate what the data is. This is often done with tag or type data at the start of each message. Sometimes a byte will do (depending on how many different message types you have). You then read that byte from the stream and decide what to deserialize next. e.g. if you want to send a string, you might serialize '1', then the string
. If you want to send a date/time, you might serialize '2' then the DateTime
. On the server, if both of those objects got sent about the same time, you could simply deserialize the byte
, and if it was '1', deserialize a string
, then continue deserializing: get the next byte
, and if it's a '2', deserialize a DateTime
.
It's important to remember that TCP is a stream-based protocol, not a message-based protocol. Message-based needs to be implemented at the application level--e.g. something like the above.
And by "serialize" and "deserialize" I mean the typical built-in serializers and deserializers as described in Serializing Objects in the .NET documentation. The same would hold true for JSON serializers included in libraries like JSON.NET or the built-in DataContractJsonSerializer
and JavaScriptSerializer
.