udp 傳輸,可解決中文不能正確傳輸,亂碼問題

來源:互聯網
上載者:User

剛開始,按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);}}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.