package 第十二章; import java.io.IOException; import java.net.*; public class UDPServer { /*** * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.println("服务器开启成功"); DatagramSocket socket=new DatagramSocket(55555); while(true){ byte[]b=new byte[1024]; // UDP以数据包的形式发送 DatagramPacket packet=new DatagramPacket(b,b.length); socket.receive(packet); String s=new String(packet.getData(),0,packet.getLength()); // 获得到发送端的IP String ip=packet.getAddress().toString(); System.out.println(ip+":"+s); } } } //客户端 ackage 第十二章; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; public class UDPClient { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub while(true){ Scanner scan=new Scanner(System.in); System.out.println("请输入要发送的数据"); String str =new String(); str=scan.nextLine(); byte[]b=str.getBytes(); // 服务器端的IP地址 InetAddress serverAddress=InetAddress.getByName("192.168.1.179"); // 参数列表:字节数组,数组的长度,服务器的IP地址,服务器的端口号 DatagramPacket packet=new DatagramPacket(b,b.length,serverAddress,55555); // DatagramSocket可以将这个数据包发送到服务器 DatagramSocket socket=new DatagramSocket(); socket.send(packet); } } }
时间: 2024-11-13 11:20:00