对话机器人代码
服务器端代码:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
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.*;
import java.util.Scanner;
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 client=new DatagramSocket();
Scanner scanner=new Scanner(System.in);
while (true){
System.out.println("我:");
String msg=scanner.nextLine();
//2.给服务器端发送消息
DatagramPacket datagramPacket=new DatagramPacket(
msg.getBytes(),
msg.getBytes().length,
InetAddress.getByName(ip),
port
);
client.send(datagramPacket);
DatagramPacket serPacket=new DatagramPacket(
new byte[bleng],
bleng
);
client.receive(serPacket);
//接收到服务器端返回信息
String serMsg=new String(serPacket.getData());
System.out.println("对方:"+serMsg);
}
}
}
udp服务端发布
1.点击项目属性
2.配置打包项
3.打包
4.使用命令启动jar
Java -jar xxx.jar