用java写基于UDP协议的简易聊天机器人
时间: 2024-02-25 11:55:41 浏览: 75
基于TCP协议网络socket编程-简单聊天机器人(java实现C/S通信)
5星 · 资源好评率100%
好的,以下是基于UDP协议的简易聊天机器人的Java代码:
客户端代码:
```java
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true) {
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
}
}
}
```
服务器端代码:
```java
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
```
这里的聊天机器人简单地将用户输入的字符串转换为大写字母后返回。如果需要实现更复杂的聊天机器人,可以使用ChatterBot等库来实现。
阅读全文