通过TCP Sockets发送命令的最好方法是什么? [英] What's the best way to send commands through TCP Sockets?

查看:484
本文介绍了通过TCP Sockets发送命令的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用的服务器和客户端使用简单的字符串到字节在它们之间发送命令。下面是基本上这样(以一个消息发送到服务器为例):

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]

并假设 recievedstring.Split(':')[1] 参数。如果用户在其消息中输入冒号,那么它将在那里切断。我觉得这是一个hacky的方式在两个端点之间发送数据。有更标准的方法吗?对不起,如果我没有提供足够的信息,我是新的!

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!

推荐答案

您不一定需要处理所有数据以字符串形式传递,可以以字节形式传输数据,然后将字节转换为任何数据类型(由发送者发送)。

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).

一个更好的方法是定义一个协议包格式)在服务器和客户端之间为每个msg。例如,您可以定义一个数据包,前4个字节包含消息的长度,后跟指定长度的消息。您的数据包格式为[length:data]

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]

在发送端,您需要首先写入长度的消息,然后写入实际数据,接收端你将首先接收一个int(长度的数据),然后接收这么多的字节。

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.

更进一步,而不是只是$ msg可以存在可以在端点之间通信的多种类型的分组,例如, $ command,$ notification等,你也可以在你的包中定义一个消息类型的字段。您的数据包格式将成为[length:type:data]

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]

这篇关于通过TCP Sockets发送命令的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆