package UDP2;import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;/*
* 完成UDP 通信快速入门 实现发1收1*/
public class Client {public static void main(String[] args) throws Exception{// 1创建客户端对象DatagramSocket socket= new DatagramSocket();//2创建数据包对象封装要发出去的数据/* public DatagramPacket(byte buf[], int length,InetAddress address, int port)参数一 封装要发出去的数据参数二 我要发的参数大小参数三 服务端IP地址参数四 服务端端口*/Scanner sc=new Scanner(System.in);while (true) {System.out.println("请说:");String msg= sc.nextLine();byte[] bytes= msg.getBytes();// 用户输入exit命令 退出客户端if ("exit".equals(msg)){System.out.println("欢迎下次光临! 退出成功!");socket.close(); //释放资源break; //跳出去循环}DatagramPacket packet =new DatagramPacket(bytes,bytes.length,InetAddress.getLocalHost(),6666);// 3:开始正式发送数据包的数据发出去socket.send(packet);}}
}
package UDP2;//完成UDP通信服务端import java.net.DatagramPacket;
import java.net.DatagramSocket;public class Server {public static void main(String[] args) throws Exception{//1创建一个服务端对象System.out.println("---------服务端启动---------");DatagramSocket socket= new DatagramSocket(6666);//2 创建数据对象用接收数据byte [] buffer=new byte[1024*64]; //1KB * 64= 64KBDatagramPacket packet=new DatagramPacket(buffer,buffer.length);while (true) {//3:开始正式设用数据包接收客户端发来的数据socket.receive(packet);//4:字节数组中的数据打印出来//接收多少倒出多少int lin= packet.getLength();String rs=new String(buffer,0,lin);System.out.println(rs);System.out.println(packet.getAddress().getHostAddress());System.out.println(packet.getPort());System.out.println("============================================");}}
}