UDP传输中文乱码、异常解决

Java socket编程,遇到UDP传输中文乱码、传输内容被异常截断等问题,查阅网上资料建议使用流的方式解决,所以试了一下,问题解决。

完整代码如下:

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

你可能感兴趣的:(Java)