分为客户端与服务器端两部分:
其中服务器端代码:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* UDP服务器端
*/
public class UDPServer {
//端口号
private static final int port = 9001;
//数据的最大值
private static final int bleng = 1024;
public static void main(String[] args) throws IOException {
//1.启动一个UDP服务器端(IP,端口号)
DatagramSocket socket = new DatagramSocket(port);
System.out.println("服务器已经启动");
while(true) {
//2.初始化数据包
DatagramPacket clientPacket = new DatagramPacket(new byte[bleng], bleng);
//3.等待客户端的连接
socket.receive(clientPacket);
//此时表明已经有客户端连接
//4.接收客户端的信息
String msg = new String(clientPacket.getData());
System.out.println("接收到客户端的信息:" + msg);
//给客户端一个响应
String serMsg = msg.replace("吗?",".");
//发送消息
DatagramPacket serPacket = new DatagramPacket(serMsg.getBytes(), serMsg.getBytes().length, clientPacket.getAddress(), clientPacket.getPort());
socket.send(serPacket);
}
}
}
客户端编程如下:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
/**
* UDP客户端
*/
public class UDPClient {
//服务器的IP
private static final String ip = "1.116.103.131";
//服务器的端口号
private static final int port = 9001;
//数据的最大长度
private static final int bleng = 1024;
public static void main(String[] args) throws IOException {
//1.启动客户端
DatagramSocket client = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("我:");
String msg = sc.nextLine();
//2.给服务器端发送消息
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),msg.getBytes().length, InetAddress.getByName(ip),port);
client.send(datagramPacket);
//3.接收服务器的返回信息
DatagramPacket serPacket = new DatagramPacket(new byte[bleng],bleng);
client.receive(serPacket);
//4.接收到服务器的返回信息
String serMsg = new String(serPacket.getData());
System.out.println("对方:"+serMsg);
}
}
}