发送端
import java.io.IOException;
import java.net.*;
import java.util.Scanner;public class send {public static void main(String[] args) throws IOException {//1.创建对象datagramSocket的对象DatagramSocket ds = new DatagramSocket();//2.打包数据Scanner sc = new Scanner(System.in);while(true){System.out.println("输入");String str = sc.nextLine();if("exit".equals(str)){break;}byte[] bytes = str.getBytes("UTF-8");InetAddress address = InetAddress.getByName("192.168.122.18");int port = 10086;DatagramPacket dp = new DatagramPacket(bytes,bytes.length,address,port);//发送数据ds.send(dp);}//释放资源ds.close();}
}
接受端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;public class receive {public static void main(String[] args) throws IOException {//1.创建对象DatagramSocket的对象DatagramSocket ds = new DatagramSocket(10086);//2.接受数据包byte[] bytes = new byte[1024];DatagramPacket dp = new DatagramPacket(bytes,bytes.length);while(true){ds.receive(dp);//3,解析数据包byte[] data = dp.getData();int len = dp.getLength();String ip = dp.getAddress().getHostName();String name = dp.getAddress().getHostName();//4.打印数据System.out.println("ip为:"+ip+",主机名为"+name+",的人,发送了数据:"+new String(data,0,len));}}
}
演示效果,虚拟机和宿主机相互连接
最终效果