System include some clients and server. Client send message to server have 3 types of message:
<IP addr server>
: <port addr server>
<IP address client>
: <port addr client>
, a link TCP connection will be established between the client and server chat. After the TCP connection is set, the client sends the connection setup information, including some fields:
Server receive this message. Then create a connection to client 2.
When receiving data sent from client 1, chat server transfer text messages from client 1 to client 2 (client 2 also using data exchange message).
So my question is: how do I send the message with some field? I already know send string by function send(). Here I have to send message Connection Setup or Data exchange with some field then I whether used pack in client side then unpack in server side or not? Please give me some solution for this problem?
I think use:
typedef struct _ConnectionSetup_Message
{
int message_ID; // 0 ConnectionSetup message
unsigned int Port;
unsigned shor IP;
} HELLO_Message;
typedef struct _DataExchange_Message
{
int message_Length;
int message_ID; // 1 for DataExchange message
char *text;
} DataExchange_Message;
You should try it yourself, its very educational. Some short advice, though:
EDIT For a c-language example you might look at eg https://stackoverflow.com/questions/5759043/sending-message-over-tcp-ip-using-sockets
Use serialization for your structures. And be aware never send pointers, but fully serialized data(strings). For more information read https://stackoverflow.com/a/1654822/2294017 and Serialize and send a data structure using Boost? . Also http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/ can be handy if you need to dive deeper.
Maybe you can try to send an identifier for the kind of message and then send the struct with a len of sizeof(your_struct), and read it on the other side the same way.
for exemple:
server side:
write(socket, &flag, sizeof(flag));
write(socket, &your_struct, sizeof(DataExchange_Message));
and then on the client side:
read(socket, &flag, sizeof(flag));
//and according to the flag you can do what you want because you know what you are going to receive
read(socket, &your_struct, sizeof(your_struct));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.