Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

TCP Programming: how to separate received packets?

Status
Not open for further replies.

Davis

Junior Member level 3
Junior Member level 3
Joined
Jul 25, 2002
Messages
29
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
156
tcp programming

I use TCP socket to send data over Ethernet. I get packets jointed in received port. I need to separate them in application program. Suppose TCP should not work like this. Any settings I missed? Please help me. Thanks.
 

Re: TCP Programming Problem

TCP gives you a 'stream of bytes' connection, exactly as you describe you have found. Your application has to encode your data into the connection, and (of course) decode it when it comes out.

The simplest way of doing this is probably to 'encode' to ascii (e.g. using sprintf) and use \n to seperate messages. Each message would start with a unique string of characters to indicate what the data which follows it is about. To decode it you would get a line from the socket (terminated by \n), and then use sscanf to get the string to identify the message, and depending on the message decode the rest of the data on the line.

If you need to send binary data (e.g. because encoding to ASCII would be too slow/overload the communications link) the principles are still the same, but you will have to code the routine to figure out where each message ends.

When you send data on a TCP connection, it may be fragmented (so it arrives at the destination in several distinct chunks) or be combined with other data (so it arrives in a bigger chunk than was sent), although the stream of bytes is not corrupted. Your application has to collect all the data chunks which make up a message and not unnecessarily discard any extra data which arrives after it (because this is probabl the start of the following message).

All this is pretty much how any stream communication link works, not a problem unique to TCP.

If you are prepared to code for detecting lost messages, or you are prepared to trust your communications medium (i.e. ethernet) not to lose any data, then you might instead choose to use UDP which delivers data on a 'message' basis: if you put 273 bytes in one socket write, the receiving end will get the 273 bytes in one received message, so there are none of the stream-decoding issues. BUT UDP does not have the 'reliable delivery' features built into it that TCP has, and your application will have to provide them if they are needed.

HTH
Barny
 
Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top