DatagramSocket此类表示用来发送和接收数据报包的套接字。
DatagramPacket此类表示数据报包。
package cn.sxt.UdpDemo; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class ClientB { public static void main(String[] args) throws IOException { //创建一个datagram socket 用于结束 DatagramSocket ds = new DatagramSocket(9000); while(true) { //接收客户端A的信息 byte[] recbuf = new byte[1024]; DatagramPacket recDp = new DatagramPacket(recbuf, recbuf.length); ds.receive(recDp); String recMsg = new String(recbuf,0,recDp.getLength()); System.out.println("clientA说"+recMsg); //发送信息到客户端A System.out.println("请输入"); Scanner sc = new Scanner(System.in); String msg = sc.next(); System.out.println("开始发送数据:"+msg); InetAddress toIp = InetAddress.getLocalHost(); byte[] buf = msg.getBytes(); // 构造数据报包,用来将长度为 length 偏移量为 offset 的包发送到指定主机上的指定端口号。 DatagramPacket dp = new DatagramPacket(buf,buf.length,toIp,8000); //发送数据报 ds.send(dp); //ds.close(); } } }
package cn.sxt.UdpDemo; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class ClientA { public static void main(String[] args) throws IOException { //创建数据报套接字并将其绑定到本地主机上的指定端口8000 DatagramSocket ds = new DatagramSocket(8000); while(true) { System.out.println("请输入"); Scanner sc = new Scanner(System.in); String msg = sc.nextLine(); //发送信息到客户端B System.out.println("开始发送数据:"+msg); byte[] buf = msg.getBytes(); InetAddress toIp = InetAddress.getLocalHost(); // 构造数据报包,用来将长度为 length 偏移量为 offset 的包发送到指定主机上的指定端口号。 DatagramPacket dp = new DatagramPacket(buf,buf.length,toIp,9000); //用数据报包的套接字,通过8000发送数据报 ds.send(dp); //接收客户端B的信息 byte[] recBuf = new byte[1024]; DatagramPacket recDp = new DatagramPacket(recBuf,recBuf.length); //信息接收 ds.receive(recDp); String recMsg = new String(recBuf,0,recDp.getLength()); System.out.println("clientB说:"+recMsg); //ds.close(); } } }