客户端:
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
/**
* UDP客户端
*/
public class UDPClient {
//服务器端的IP地址
private static final String ip = "127.0.0.1";
//服务器的端口号
private static final int port = 9001;
//数据包你的大小
private static final int bleng = 1024;
public static void main(String[] args) throws IOException {
//1、创建客户端
DatagramSocket socket = new DatagramSocket();//动态的一个端口号
//让用户来输入发送输入的信息
Scanner sc = new Scanner(System.in);
while (true){
System.out.println("->");
//接收到用户输入的信息
String msg = sc.nextLine();
//2、构建发送数据包
DatagramPacket datagramPacket = new DatagramPacket(
msg.getBytes(),
msg.getBytes().length,
InetAddress.getByName(ip),
port
);
//3、发送消息
socket.send(datagramPacket);
//接收服务器端的反馈信息
DatagramPacket serPacket = new DatagramPacket(
new byte[bleng],bleng);
socket.receive(serPacket);
System.out.println("收到服务器的信息:"+new String(serPacket.getData()));
}
}
}
服务器端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
/**
* UDP服务器
*/
public class UDPServer {
//端口号
private static int port = 9001;
private static int bleng = 1024;
public static void main(String[] args) throws IOException {
//1、创建一个UDP服务器
DatagramSocket socket = new DatagramSocket(port);
while (true){
DatagramPacket clientPacket = new DatagramPacket(
new byte[bleng],bleng);//服务器容器和大小
//等待客户端的连接
socket.receive(clientPacket);
//执行此代码表示已经有客户端连接
//3.拿到客户端的请求信息
String msg = new String(clientPacket.getData());
System.out.println("接收到客户端的信息:"+msg);
//给客户端反馈一个消息
String serMsg = "我收到了";
//构建客户端发送数据包
DatagramPacket serPacket = new DatagramPacket(
serMsg.getBytes(),
serMsg.getBytes().length,//注意是字节数组的长度
clientPacket.getAddress(),
clientPacket.getPort()
);
//给客户端发送消息
socket.send(serPacket);
}
}
}
结果展示: