网络通信替代字符串 [英] Network communication alternative to Strings

查看:100
本文介绍了网络通信替代字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在大多数客户端/服务器通信示例中,字符串被编码为字节数组作为消息,我需要更强大的功能,因为我需要发送命令和参数,有时还需要发送图像.
在不是字符串的字节数组中编码的最佳方法是什么?
我不想拆分以了解命令及其参数.

in most examples of client / server communication a string is encoded to an array of bytes as a message, I would need something more powerful, because I need to send commands and parameters, and sometimes images.
What is the best thing to be encoded in a byte array that is not a string?
I do not want to split in order to understand what is the command and its parameters.

推荐答案

您可以在字节数组的开头添加命令头"它由已知的长度(例如64或128字节,甚至更大)组成(给您增长的空间).然后,只需将命令/参数值插入该区域.只要发送和接收应用程序都知道此标头,他们就可以对其进行处理.

此时,您可以使标头包含所需的任何内容,包括整数,字符串(转换为十六进制字节),DateTime对象等.只要两个应用程序都知道如何处理它(我将使用一个单独的程序集即可这两个应用程序参考),你是黄金.

哎呀,您甚至可以将一个对象序列化为字节数组,在开始处添加几个字节来描述其长度,然后在该字节数组前添加THAT.
You could add a "command header" to the beginning of your byte array that is comprised of a known length, say 64 or 128 bytes or even larger (to give you room to grow). Then, you just plug in your command/param values into that area. As long as both the sending and receiving apps are aware of this header, they can process it.

At that point, you can make the header contain anything you want, including integers, strings (converted to hex bytes), DateTime objects, etc. As long as both apps know how to process it (I would use a separate assembly that both apps reference), you''re gold.

Heck, you could even serialize an object to a byte array, add a couple of bytes at the beginning to describe it''s length, and pre-pend THAT to your byte array.


字节数组不能替代字符串,字节数组是对每种可能数据的抽象序列化表示.您可能无法传输其他任何内容,可以吗? :-)

真正的选择是传输二进制数据,如果您需要最佳性能,我建议您这样做.不用说,无论如何该数据都将被序列化为字节数组,但是字节的数量可以大大减少.

—SA
An array of bytes is not an alternative to string, an array of bytes is an abstract serialized representation of every data possible. You cannot possibly transmit anything else, can you? :-)

The real alternative is transmitting binary data, which I would recommend if you need top performance. Needless to say, this data will be serialized to an array of bytes anyway, but the amount of bytes can be essentially reduced.

—SA


这篇关于网络通信替代字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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