本文主要是介绍基于 Java 实现的智能客服聊天工具模拟场景,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
服务端代码
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket;public class Server {public static void main(String[] args) throws IOException {try (ServerSocket serverSocket = new ServerSocket(12231)) {while (true) {Socket socket = serverSocket.accept();new Thread(new ServerHandler(socket)).start();}}}static class ServerHandler implements Runnable {private Socket socket;public ServerHandler(Socket socket) {this.socket = socket;}@Overridepublic void run() {try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true);BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {String inputLine;while ((inputLine = in.readLine()) != null) {System.out.println("客户端:" + inputLine);if ("bye".equalsIgnoreCase(inputLine)) {break;}String baobao= "智能客服回答了"+Math.random();out.println("客户端问:" + inputLine+" 服务端回:"+baobao);}} catch (IOException e) {e.printStackTrace();} finally {try {socket.close();} catch (IOException e) {e.printStackTrace();}}}} }
客户端代码
import java.io.*; import java.net.Socket;public class Client {public static void main(String[] args) throws IOException {try (Socket socket = new Socket("127.0.0.1", 12231);PrintWriter out = new PrintWriter(socket.getOutputStream(), true);BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {String userInput;while ((userInput = stdIn.readLine()) != null) {out.println(userInput);if ("bye".equalsIgnoreCase(userInput)) {break;}System.out.println("服务器:" + in.readLine());}}} }
模拟结果:
what is your name ?
服务器:客户端问:what is your name ? 服务端回:智能客服回答了0.9437969215616254
请亮出你的身份
服务器:客户端问:请亮出你的身份 服务端回:智能客服回答了0.01275853034904273
这篇关于基于 Java 实现的智能客服聊天工具模拟场景的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!