0

I'm trying to send multiple packets from a tcp server to a client using only read and write from the base "Stream" class. The problem is, I don't know what the size of the packet will be (client side). Should I send and int (4 bytes) before each packet so the client can ajust the buffer and receive only the nuber of bytes specified? I feel like there's already something in the tcp protocol that handles that but I can't seem to find it.

4
  • I feel like there's already something in the tcp protocol that handles that. No there is not. Commented Feb 15, 2015 at 18:14
  • You are not sending packets, you are writing to a stream. One call to Write or Read != one packet sent by tcp Commented Feb 15, 2015 at 18:16
  • @ScottChamberlain I understand that, but my question was more like "Is it necessary to implement a packet size prefix to be able to send packet?" Commented Feb 15, 2015 at 18:29
  • Yes, sending a 4-byte int is probably the best approach, if you don't have a fixed size message format. That way on your receiving end you read four bytes, decode that to and int n, then read n more bytes. Commented Feb 15, 2015 at 18:30

1 Answer 1

0

The process for what you are wanting to do is called Message Framing and there is no built in mecinism in TcpClient that does this for you. It is the responsibility of the higher level application layer to do it, be it your own code appending the length on the prefix of the message or some other library that handles message framing for you like WCF.

Here is a full example showing a length prefixed implementation like you suggested in your question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.