What's the best way to send commands through T

2019-05-31 22:55发布

问题:

What I'm currently doing with my Server and Client is sending commands between them using simple strings to bytes. What it comes down to is basically this (to send a message to the server as an example):

byte[] outStream = System.Text.Encoding.UTF8.GetBytes("$msg:Test Message");
serverStream.Write(outStream, 0, outStream.Length);

And the recieving end encodes back to a string. It recognizes the command by doing this:

recievedstring.Split(':')[0]

and assuming that recievedstring.Split(':')[1] is the argument. If a user entered a colon in their message then it would cut off there. I feel like this is a hacky way to send data between both endpoints. Is there a more standard way to do this? Sorry if I didn't provide enough information, I'm new to this!

回答1:

You dont necessarily need to deal all data communicated as string, you can communicate data as bytes and later convert bytes to any datatype(as sent by sender).

A better way is to define a protocol (e.g. a packet format) between server and client for each msg. For example, you can define a packet such that first 4 bytes contain length of the message followed by the message of specified length. Your packet format will be [length:data]

On sending side you will need to write length of message first on stream, and then write the actual data, where as on receiving side you will first receive an int (length of data) and then receive that much byte.

Further more, instead of just $msg (as in your case) if there can be multiple types of packets that can be communicated between end points e.g. $command, $notification etc you can also define a field of message type in your packet. Your packet format will become [length:type:data]