编写程序,观察UDP方式的数据传输

import java.net.*;
import java.io.*;

public class UDPServer{
    
    public static void main(String[] args){
        try{
            byte[] buf = new byte[100];
            DatagramPacket dp = new DatagramPacket(buf,buf.length);
            DatagramSocket ds = new DatagramSocket(8888);
            while(true){
                ds.receive(dp);
                System.out.println(new String(buf,0,dp.getLength()));
            }
        } catch(IOException e){
            e.printStackTrace();
        }
        
    }
    
}
import java.net.*;
import java.io.*;

public class UDPClient{
    
    public static void main(String[] args){
        try{
            byte[] buf = (new String("hello!").getBytes());
            DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",8888));
            DatagramSocket ds = new DatagramSocket(9999);
            ds.send(dp);
            ds.close();
        } catch(IOException e){
            e.printStackTrace();
        }
    }
    
}

猜你喜欢

转载自www.cnblogs.com/yxfyg/p/12442408.html