通过数据报套接字发送对象java
我正在实现这个示例,因为我想广播到多个客户。在尝试使用套接字发送另一个对象(已序列化)时,我收到一条错误,指出套接字(在示例中)无法通过它发送对象。数据报套接字不能也发送/接收对象吗?
I'm implementing this example as I want to broadcast to multiple clients. While trying to use the socket to send another object(which has been serialised), I'm getting an error which says that socket(in the example) can't send the object via it. Can't a datagram socket send/receive objects also?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般而言不是,不是。数据报包通常相对较小 - 您可以尝试将对象序列化为包装在
ObjectOutputStream
中的ByteArrayOutputStream
,然后尝试发送字节数组之后 - 但您可能会发现它很快就变得太大了。使用更高效的序列化格式(例如 协议缓冲区)可能会让您在单个数据包中获取更多信息,但通常情况下您希望序列化为流而不是单个数据包...一旦您开始尝试将基于流的协议放在数据报上 -基于协议 - 好吧,你最终合理地得到了 TCP尽快,只要它必须可靠。
如果您可以向我们提供有关您尝试执行的操作的更多详细信息(包括可靠性限制 - 如果数据包丢失有多严重?),我们也许能够为您提供更多帮助。
Not in general, no. Datagram packets are generally relatively small - you could try serializing your object to a
ByteArrayOutputStream
wrapped in anObjectOutputStream
, and then try to send the byte array afterwards - but you may well find it gets too big very quickly.Using a more efficient serialization format such as Protocol Buffers will probably allow you to get more information in a single packet, but typically you'd want to serialize to a stream instead of to a single packet... and as soon as you start trying to put a stream-based protocol over a datagram-based protocol - well, you end up with TCP reasonably quickly, as soon as it has to be reliable.
If you can give us more details of what you're trying to do (including reliability constraints - how serious is it if a packet is lost?), we may be able to help you more.
最好的选择是使用 TCP 或其他库,例如 jGroups
Your best bet is to either use TCP or another library such as jGroups