Send data over TCP/IP with sockets and serialize data
i have to send via TCP/IP with sockets a string formatted as CHARINT,INT where CHAR is a character an开发者_如何学Pythond INT are numbers. Which is the best way to send them and receive them? And how could i split that string when I receive it to have again the two integers?
There are plenty of ways to do what you need, and the choice depends on how extensible you need to the solution to be. If all you need is two integers, then you can send them by putting them to array "int arr[2];" and use send(arr, 2*sizeof(int)) call to send the data. When receiving the data you do the opposite.
Quite simple but easy to implement method to serialize small amounts of data is to convert numbers to text (using itoa()) and send a coma-separated list of values. On the other side you parse the string by simply splitting it using coma as a separator and then using atoi() to convert values back to ints.
However, for anything more complex you need more flexible scheme. Search for "serialization" on this site for various options. Any generic scheme would require a parser and it makes sense to not reinvent the wheel. ASN.1 is a universal binary protocol for serialization, extensively used in communications industry.
精彩评论