udp 传输,可解决中文不能正确传输,乱码问题

刚开始,按JDK 里的例子写,

// 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);


这样写传英文,可以,但是传中文, 就不能正确传输。

看了网上的一些说法,其中有说到用流的方法,所以,试一下,可以解决了。

完整代码如下:

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 = new MulticastSocket(srv.port);
		srv.sendMessage("萤火虫,皎白月光,游过四季",socket);
		srv.getMessage(socket);
	}

}


 

你可能感兴趣的:(udp 传输,可解决中文不能正确传输,乱码问题)