在 Java 中使用 UDP 跨网络发送对象
我还没有找到我遇到的问题的确切答案,所以无论如何我都会问这个问题,如果我确实重新发布了已经被问过的问题,我深表歉意。
我正在为我的 Java 课程做另一项实验作业,对于本周的实验,我必须创建一个 UDP 服务器来通过网络发送 Message 对象,然后我必须创建一个 UDP 客户端来读取该消息。消息本身只是一个对象,它有一个字符串消息和一个字符串用户名;相当任意。消息是可序列化的。
现在,我遇到的问题是如何在 DatagramPacket 中实际通过网络发送该消息对象?实际的构造函数让我放入一个字节数组、数组的大小、InetAddress 和端口号。我的最后一个问题是:如何找出数组的大小,以及如何将消息转换为要发送的字节?
I haven't found an exact answer to the problem that I'm having, so I'm going to ask this anyway, and if I did, in fact, repost a question that's already been asked, I apologize.
I'm doing another lab assignment for my Java class, and for this week's lab, I have to make a UDP server to send out a Message object across the network, then I have to make a UDP client to read in that Message. The Message itself is just an Object that has a String message and a String username; fairly arbitrary. Message is Serializable.
Now, what I'm having an issue with is how to actually go about sending that Message Object across the network within a DatagramPacket? The actual constructor has me put in a byte array, the size of the array, the InetAddress, and the port number. My final question is: how to I find out the size of the array, and how to I turn my Message into bytes to be sent out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将消息类序列化为字节数组。这将是您发送的字节数组(并且很容易获得此时的大小)。
在客户端,您需要将字节数组反序列化回 Message 对象。
Java提供了一组类来处理序列化/反序列化,并且要序列化的对象必须实现“Serialized”接口。
这样的事情会起作用:
在接收端:
注意,您应该创建一个在客户端和服务器之间共享的通用接口,这将允许轻松地序列化/反序列化有效负载。
You need to serialize your message class into a byte array. This will be the byte array you send (and it will be easy to get the size at that point).
On the client, you will want to deserialize the byte array back into a Message object.
Java provides a set of classes to handle serialization/deserialization, and the object you want to serialize must implement the "Serializable" interface.
Something like this would work:
And on the receiving end:
Note, you should create a common interface that is shared between the client and the server, this will allow for easy serialization/deserialization of the payload.