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 th开发者_StackOverflow社区e example) can't send the object via it. Can't a datagram socket send/receive objects also?
Not in general, no. Datagram packets are generally relatively small - you could try serializing your object to a ByteArrayOutputStream
wrapped in an ObjectOutputStream
, 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.
Your best bet is to either use TCP or another library such as jGroups
JGroups is a toolkit for reliable multicast communication.
精彩评论