服务端: 监听端口(5051),接收数据
import java.io.*;
import java.net.*;
import java.util.Scanner;
class UdpServer{
public static void main(String[] args)throws IOException{
DatagramSocket server = new DatagramSocket(5051);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
while (true) {
server.receive(recvPacket);
String recvStr = new String(recvPacket.getData(), 0,
recvPacket.getLength());
System.out.println("收到:" + recvStr);
if(recvStr.endsWith("q")|| recvStr.endsWith("quit")){
break;
}
}
server.close();
}
}
客户端:向目标IP(127.0.0.1)及端口(5051),发送字符串
import java.io.*;
import java.net.*;
import java.util.Scanner;
class UdpClient{
public static void main(String[] args)throws IOException{
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName("127.0.0.1");
int port = 5051;
byte[] sendBuf;
while(true){
Scanner sc = new Scanner(System.in);
System.out.println("请输要发送的内容:");
String str = sc.nextLine();
sendBuf = str.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuf , sendBuf.length , addr , port );
client.send(sendPacket);
if(str.endsWith("q")|| str.endsWith("quit")){
break;
}
}
client.close();
}
}