Java-网络编程-UDP
1、send方
package cn.bruce.internetkeyboard; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; /* * 实现UDP协议发送端: * 实现封装数据的类:java.net.DatagramPacket 将你的数据包装 * 实现封装传输的类:java.net.DatagramSocket 将数据包发出去 * 实现步骤: * 1、创建DatagramPacket对象,封装数据,接受的地址和端口 * 2、创建DatagramSocket,并调用send方法,发送数据报包 * 3、关闭资源 */ public class UDPSEND { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); InetAddress inet = InetAddress.getByName("127.0.0.1");// 封装接收IP DatagramSocket DS = new DatagramSocket(); while (true) { byte[] data = sc.nextLine().getBytes();// 封装数据 // 封装数据报包 DatagramPacket dPacket = new DatagramPacket(data, data.length, inet, 6033); // 发送数据 DS.send(dPacket); } // 关闭资源 // DS.close(); } }
2、receive方
package cn.bruce.internetkeyboard; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPRECEIVE { public static void main(String[] args) throws IOException { DatagramSocket datagramSocket = new DatagramSocket(6033); byte[] data = new byte[1024]; while (true) { DatagramPacket dPacket = new DatagramPacket(data, data.length); datagramSocket.receive(dPacket); System.out.println(new String(data, 0, dPacket.getLength())); } // 长度使用方法来获取 // datagramSocket.close(); } }
先运行receive,进行线程等待,再运行send,进行文字输入