What's the best way to send commands through TCP Sockets?

倾然丶 夕夏残阳落幕 提交于 2019-12-08 07:58:17

问题


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]



来源:https://stackoverflow.com/questions/26500944/whats-the-best-way-to-send-commands-through-tcp-sockets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!