创建一个可以拆分的 UDP 数据包
我正在 vb.net 中构建一个简单的 udp 局域网聊天应用程序,我想知道应该如何拆分数据包。 每个发送的数据包应该有一个 id、一个用户名和来自其来源的 IP 地址,也许还有一个命令部分,例如加入或离开以更新我的用户列表和一条短信。 我想知道什么是最简单的方法,可以将所有这些内容放入一个简单的数据包中,然后在收到数据包时轻松拆分并访问其中的不同部分。 谢谢。
我正在使用 UDP,因为这仅在局域网中,所以我正在广播到 *.*.*.255
编辑:谢谢您的回答乔恩,但我已经知道了这一切。 我想知道什么是最简单和最强大的方式来格式化我的数据包,使它们包含用户名,ID,命令和文本消息,然后接收它的用户解密它以仅显示由其编写的消息用户,或者如果它是像加入或离开这样的命令,则显示适当的加入消息并将用户添加到列表中。
I'm building a simple udp lan chat application in vb.net and I'm wondering how I should split my packets. Each sent packet should have like an id, a username and ip address from where it's coming and maybe also a command part for like join or leave to update my userlist and a text message. I'd like to know what is the easiest way to put all this in a simple packet then easily split and access different parts from it when it's received. thanks.
I'm using UDP since this is only in lan so i'm broadcasting to *.*.*.255
EDIT: Thank you for your answer Jon but I already know all that. What I want to know is what would be the most easy and powerful way to format my packets so they include a username , an id, a command and a text message, then the user receiving it decrypt it to show only the message written by which user or if it's a command like join or leave to show the appropriate message of joining and add the user to the list for exemple.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用实例
ToByteArray
方法和静态FromByteArray()
方法创建适当的类(分别用于序列化为字节数组和从字节数组解析)。 然后使用UdpClient.Send()
发送它,以及UdpClient。 Receive()
来接收它。您可能需要使用
BinaryReader
/BinaryWriter
和/或BitConverter
来帮助处理ToByteArray
和FromByteArray方法。 您可以使用
MemoryStream
作为快速内存流来传递给BinaryReader
/BinaryWriter
。Create an appropriate class with an instance
ToByteArray
method and a staticFromByteArray()
method (for serializing to a byte array and parsing from a byte array respectively). Then useUdpClient.Send()
to send it, andUdpClient.Receive()
to receive it.You may want to use
BinaryReader
/BinaryWriter
and/orBitConverter
to help with theToByteArray
andFromByteArray
methods. You can use aMemoryStream
as a quick in-memory stream to pass toBinaryReader
/BinaryWriter
.我可能只是将数据包格式化为 xml,然后在接收端使用 linq to xml 将其分开。 您还可以使用 JSON 作为格式,但这可能稍微难以解析。
I would probably just format the packet in xml and then on the receive side use linq to xml to pull it apart. You could also use JSON for the format but that might be slightly harder to parse.