基于tcp协议的简易聊天机器人要求能通过关键字回答问题用Java实现代码
时间: 2024-02-27 10:56:16 浏览: 75
基于tcp/ip用java实现的聊天程序
好的,以下是基于TCP协议的简易聊天机器人的Java实现代码示例:
服务端:
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class Server {
private static final int PORT = 8888;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("服务端已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接,IP地址为:" + socket.getInetAddress().getHostAddress());
// 模拟关键字回答
Map<String, String> keywordMap = new HashMap<>();
keywordMap.put("你好", "您好,请问有什么可以帮助您的?");
keywordMap.put("再见", "欢迎下次再来!");
keywordMap.put("天气", "今天天气晴朗,气温适宜。");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while (true) {
String msg = reader.readLine();
if (msg != null) {
System.out.println("客户端:" + msg);
String replyMsg = "不好意思,我没听懂您说的话。";
for (String keyword : keywordMap.keySet()) {
if (msg.contains(keyword)) {
replyMsg = keywordMap.get(keyword);
break;
}
}
writer.write(replyMsg);
writer.newLine();
writer.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端:
```java
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private static final String IP_ADDRESS = "127.0.0.1";
private static final int PORT = 8888;
public static void main(String[] args) {
try {
Socket socket = new Socket(IP_ADDRESS, PORT);
System.out.println("已连接服务端,可以开始聊天了!");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (true) {
String msg = scanner.nextLine();
writer.write(msg);
writer.newLine();
writer.flush();
String replyMsg = reader.readLine();
System.out.println("服务端:" + replyMsg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码示例中,我们通过socket建立连接,并在服务端模拟关键字回答,客户端输入问题后,通过socket将问题发送到服务端,服务端根据关键字匹配返回相应的答案,客户端再将服务端的回复输出到控制台。
阅读全文