在 1 个 UDP 数据报中发送多个数据
我正在做一个网络编程作业,关于编写一个简单的 IM 系统(非常类似于最简单版本的 Windows Messenger)。
规范指定我必须在单个数据报包中发送超过 4 个数据字段,它们是:
To From Type Message
where type refers to message type, implemented as a user defined enum class.
我想学习如何将所有这些数据打包到单个数据包中。
更新:感谢迄今为止的帮助, 但说我有字符串句子和字符串来自 单独修补数据包的正常方法是,
byte[] sendData = new byte [256]
sendData = sentence.getBytes();
但是我到底如何将“from”字符串与句子字符串一起附加到 sendData ?
i'm working on a network programming assignment about writing a simple IM system (pretty much like the simplest version of windows messenger).
the spec specifies that i must send over 4 fields of data in a single datagram packet, those are:
To From Type Message
where type refers to message type, implemented as a user defined enum class.
I would like to be taught how to pack all these datas into a single packet.
UPDATE: thx for the help so far,
but say i have String sentence and String From
the normal way to patch the packet individually would be
byte[] sendData = new byte [256]
sendData = sentence.getBytes();
but how exactly can i append the "from" string to sendData along with the sentence string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用类似的方法发送任何可序列化的对象。
You can send any Serializable object using something like this.
简而言之,您需要做的是:
在另一端,您将读取此字节流,反序列化并将其转换为上面 1. 中定义的类的实例。
通过创建包含 4 个字段的一个对象并序列化该对象,您可以将所有四个字段一起发送(我的印象是这是一个绊脚石?)。
请注意,数据报将受到网络传输层施加的大小限制,但对于此应用程序,我怀疑这不是问题。
Briefly, what you need to do is:
At the other end you'll read this bytestream, deserialise and cast it to an instance of your class defined in 1. above.
By creating the one object containing the 4 fields and serialising this object, this allows you to send all four fields together (I get the impression that this is the stumbling block?).
Note that datagrams will have size limits imposed by the network transport layers, but for this application I suspect that's not a problem.
您只需在将它们传递到网络接口之前附加它们即可。 大致如下:
如果它们不都是字符串,则需要对它们进行编码。
You simply append them before passing them to the network interface. Something along the lines of:
If they're not all strings, you'll need to encode them as such.
有很多用于编码数据的选项,所有这些选项都可以归结为将四个字段放入一个数据结构中,然后一次性发送。
重要的部分是编码需要显示四个字段中的哪一个位于数据包,否则远端将无法可靠地对其进行解码。
There are plenty of options for encoding the data, all of which come down to putting the four fields into one data structure, and then sending that all in one go.
The important part is that the encoding needs to show which of the four fields is at which point in the packet, otherwise the far end won't be able to decode it reliably.