本文实例为大家分享了java实现聊天机器人的具体代码,供大家参考,具体内容如下
服务器的代码:
package day02;import .io.*;import java.net.*; public class socket1 { public static void main(string[] args) throws exception{ int port=8899; serversocket server=null; mchat mc=new mchat(); try { server=new serversocket(port); system.out.println("服务器启动..."); while(true) { socket socket=server.accept();//监听客户端连接,如果客户端连接成功,返回实例化的socket对象 system.out.println("客户端信息:" socket); //读取流操作 socketthd thd=new socketthd(socket); thd.start(); } } catch (exception e) { // todo: handle exception } finally { try { if(server!=null) server.close(); system.out.println("服务器已停止! "); } catch (exception e2) { // todo: handle exception } } } static class socketthd extends thread{ mchat mc=new mchat(); socket socket;//和客户端进行通信的对象 bufferedreader br=null; printwriter pw=null; public socketthd(socket socket) { this.socket=socket; } public void run() { //读入流操作 try { br=new bufferedreader(new inputstreamreader(socket.getinputstream(),"utf-8")); //写入流操作 pw=new printwriter( new bufferedwriter(new outputstreamwriter(socket.getoutputstream(), "utf-8"))); //接收客户端发送来的信息 string str=""; while((str=br.readline())!=null) { system.out.println("客户端:" str); //服务器处理 string rtn=""; //聊天机器人处理程序 rtn=mc.getcharresult(str); //处理结果返回客户端 pw.println(rtn); pw.flush(); } } catch (exception e) { e.printstacktrace(); } finally { // todo: handle finally clause try { if(br!=null) br.close(); if(pw!=null) pw.close(); if(socket!=null) socket.close(); } catch (exception e2) { // todo: handle exception } } } }}
客户端的代码:
package day02; import java.io.bufferedreader;import java.io.bufferedwriter;import java.io.inputstreamreader;import java.io.outputstreamwriter;import java.io.printwriter;import java.net.socket; public class client1 { public static void main(string[] args) throws exception{ string ip="192.168.1.*"; int port=8899; socket socket=new socket(ip,port);//建立与服务器连接 //读取流操作 bufferedreader br=new bufferedreader(new inputstreamreader(socket.getinputstream(), "utf-8")); bufferedreader brkey=new bufferedreader(new inputstreamreader(system.in, "utf-8")); //写入流操作 printwriter pw=new printwriter( new bufferedwriter(new outputstreamwriter(socket.getoutputstream(), "utf-8"))); while(true) { string send=brkey.readline();//等待阻塞命令 if(send.equals("end")) {//键盘输入的借宿条件 break; } //向服务器发送信息 pw.println(send); pw.flush(); //接收服务端回复的消息 string strrtn=br.readline(); system.out.println("服务端回复信息:" strrtn); } //关闭连接 br.close(); pw.close(); socket.close(); }}
对话内容引擎:
package day02; import java.util.hashtable; public class mchat { private hashtable
实现结果如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持软科小院。