At the beginning, follow the example in JDK to write,
// join a Multicast group and send the group salutations ... String msg = "Hello"; InetAddress group = InetAddress.getByName("228.5.6.7"); MulticastSocket s = new MulticastSocket(6789); s.joinGroup(group); DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), group, 6789); s.send(hi); // get their responses!byte[] buf = new byte[1000]; DatagramPacket recv = new DatagramPacket(buf, buf.length); s.receive(recv); ... // OK, I'm done talking - leave the group... s.leaveGroup(group);
In this way, you can write the English text, but the Chinese text cannot be transmitted correctly.
After reading some online statements, some of them use the stream method. So, try it and solve it.
The complete code is as follows:
Public class mudpsrv {int Port = 6789; Public void sendmessage (string MSG, multicastsocket socket) throws ioexception {bytearrayoutputstream ostream = new bytearrayoutputstream (); dataoutputstream datastream = new dataoutputstream (ostream ); datastream. writeutf (MSG); datastream. close (); byte [] DATA = ostream. tobytearray (); inetaddress address = inetaddress. getbyname ("230.3.3.3"); socket. joingroup (Address); datagrampacket dp = new datagrampacket (data, data. length, address, Port); socket. send (DP);} public void getmessage (multicastsocket socket) throws ioexception {byte [] BS = new byte [1000]; datagrampacket packet = new datagrampacket (BS, BS. length); socket. receive (packet); datainputstream istream = new datainputstream (New bytearrayinputstream (packet. getdata (), packet. getoffset (), packet. getlength (); string MSG = istream. readutf (); system. out. println (MSG);} public static void main (string ARGs []) throws ioexception {mudpsrv SRV = new mudpsrv (); multicastsocket Socket socket = new multicastsocket (SRV. port); srv. sendmessage ("Firefly, moonlight, Four Seasons", socket); srv. getmessage (socket );}}