tags:

views:

1155

answers:

3

C#: How should TCP socket buffer data be handled? As bytes or converted to an ascii string?

I am using methods that are involved in parsing specific data from the returned tcp socket buffer, which practice would be best?

Should I process/parse my data in it's raw byte form? Or should I process it after convert it to an ascii string since string datatypes have niftier text operations?

+2  A: 

In general, as bytes. It's basically binary data - it's up to the protocol above TCP that to interpret that binary data appropriately.

Now, what is your data? Are you in control of the protocol? If so, is it meant to be text data? Converting binary data for an image (for example) into ASCII is likely to be disastrous... but if it's a genuinely ASCII-only protocol, it's probably the right way to go.

If you don't know the protocol, don't perform any conversions: they may well lose information unless you're very careful (e.g. using base64 instead of just an ASCII encoding).

If you do know the protocol, that should dictate how you treat the data.

Jon Skeet
A: 

Actually the buufer data is aways "raw" bytes, so if you want to parse the content you'll have to convert the byte[] into a string. For exemple:

string myString = Encoding.ASCII.GetString(myBufferData);
Eduardo Cobuci
A: 

I think it depends on the data being contained in the buffer. If it's a string it's convenient to convert the buffer to a string.

Also note, that you should prepend some header data before you send the string. Like length of the data payload, checksum/parity etc. Network is a non-deterministic environment, and you can't say for sure who sends what on a specified port, you might get a hard-to-trace crashes if you just convert the received buffer directly into a string.

arul