htofly 2019-12-16
先启用服务器端,再启动客户端,然后查看服务器端的console结果
public static void main(String[] args) throws IOException{ System.out.println("服务端启动"); //创建客户端 DatagramSocket server = new DatagramSocket(9917); //创建容器 byte[] container = new byte[1024*60]; //创建packet DatagramPacket packet = new DatagramPacket(container,0,container.length); //接收数据 server.receive(packet); //处理数据 System.out.println(new String(container,0,container.length)); //关闭 server.close(); }
public static void main(String[] args) throws IOException{ System.out.println("客户端启动"); //创建客户端 DatagramSocket client = new DatagramSocket(12454); //准备数据 String str = "最后一遍了"; byte[] datas = str.getBytes(); //创建packet DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",9917)); //发送 client.send(packet); //关闭 client.close(); }
运行结果:
服务端启动 最后一遍了