求用JAVA做一个聊天机器人

求用JAVA做一个聊天机器人,第1张

- -!这东西也太简单了吧

improt javautilScanner;

public class chatRobit() {

Scanner scan = new Scanner(Systemin);

boolean flag = true;

public static void main(String[] args) {

while(flag){

String str = scannextLine();

if(strequlas("你好")) {

Systemoutprintln("你好");

} else if(strequlas("再见")) {

Systemoutprintln("再见");

thisflag = false;

} else {

Systemoutprintln("对不起,我不知道你在说什么");

}

}

Systemexit(0);

}

}

话说网上真的好多啊

package client;

import javaawtColor;

import javaawtContainer;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaawteventWindowAdapter;

import javaawteventWindowEvent;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioIOException;

import javanetSocket;

import javautilDate;

import javaxswingJButton;

import javaxswingJFrame;

import javaxswingJOptionPane;

import javaxswingJScrollPane;

import javaxswingJTextArea;

import javaxswingJTextField;

public class ClientFrame extends JFrame{

private JTextArea allmsg;

private JTextField welcome,copyright,chatmsg;

private JButton send;

private JScrollPane js;

private boolean isConnected = true;

public DataOutputStream out;

public DataInputStream in;

public Socket s = null;

String nic; / -- 保存用户昵称 --/

/

初始化客户端资源

1获取从LoginFrame传递过来的参数

2初始化界面元素

3初始化通信所需要的资源 EG:输入/输出流(DataInputStream/DataOutputStream)

/

public ClientFrame(String name,Socket socket)

{

thissetSize(310,660);

thissetLocation(290,50);

thissetTitle("聊天室客户端<"+name+">");/ -- 指定窗口的标题 --/

thiss = socket;/ -- 接收从LoginFrame中传递过来的Socket --/

thisnic = name+" 说: ";

welcome = new JTextField(" < "+name+" >欢迎您来到聊天室 ",100);

welcomesetBackground(Colorblue);

welcomesetEnabled(false);

copyright = new JTextField(" ----- all copyright @ TOP-king -----");

copyrightsetEnabled(false);

allmsg = new JTextArea();

allmsgsetEditable(false);

allmsgappend(" 系统消息: 欢迎登录在线聊天室 \n");

js = new JScrollPane(allmsg);//为JTextArea添加滚动条

chatmsg = new JTextField("在此输入聊天信息");

chatmsgaddActionListener(new listen());

send = new JButton("发送");

sendaddActionListener(new listen());/ -- 添加事件监听器 --/

try {

out = new DataOutputStream(sgetOutputStream());

in = new DataInputStream(sgetInputStream());

} catch (IOException e) {JOptionPaneshowMessageDialog(null, "系统异常","错误",JOptionPaneOK_CANCEL_OPTION);}

addcomponettocontainer();

/ -- 当用户关闭窗口时进行相关的处理 eg:Socket Data(Input/Output)Stream 的关闭--/

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we)

{

sendmsg("quit&logout");/ -- 向服务器端发送关闭信息 --/

isConnected = false;

destory();/ -- 销毁窗口资源 --/

}

});

new Thread(new linread())start();/ -- 启动读取信息线程 --/

}

public void addcomponettocontainer()

{

Container c = thisgetContentPane();

csetLayout(null);

welcomesetBounds(75,10,150,20);

jssetBounds(10,50,280,500);

chatmsgsetBounds(10,560,180,30);

sendsetBounds(220,560,70,30);

copyrightsetBounds(10,600,280,20);

cadd(welcome);

cadd(js);

cadd(chatmsg);

cadd(send);

cadd(copyright);

thissetVisible(true);

thissetResizable(false);

}

class listen implements ActionListener

{

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

if(egetSource()==send||egetSource()==chatmsg)

{

String msg = chatmsggetText()trim();

if(""equals(msg))

{

JOptionPaneshowMessageDialog(null,"发送信息不能为空!","错误",JOptionPaneOK_OPTION);

}

else

{sendmsg((new Date())toLocaleString()+"\n"+nic+msg+"\n");chatmsgsetText("");}

}

}

}

/ -- 向服务器端发送信息 --/

public void sendmsg(String m)

{

if(isConnected)//如果socket的输出流没关闭

{

try {

outwriteUTF(m);

} catch (IOException e) {

JOptionPaneshowMessageDialog(null,"发送信息失败!(系统异常)","错误",JOptionPaneOK_OPTION);

}

}

else

{

JOptionPaneshowMessageDialog(null,"发送信息失败!(服务器关闭/网络故障)","错误",JOptionPaneOK_OPTION);

}

}

/ -- 读取信息线程 --/

class linread implements Runnable

{

public void run()

{

read();

}

public void read()

{

while(isConnected)

{

try {

String msg = inreadUTF();

if("SYSTEM_CLOSED"equals(msg))

{

JOptionPaneshowMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPaneOK_OPTION);

isConnected = false;

}

else

allmsgappend(msg+"\n");

} catch (IOException e) {

}

}//end while

JOptionPaneshowMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPaneOK_OPTION);

}//end read()

}

public void destory()

{

try {

thisoutclose();

thisinclose();

thissclose();

} catch (IOException e) {

}

thisdispose();

}

}

======================================================

package client;

import javaawt;

import javaxswing;

import javaawtevent;

import javaio;

import javanet;

public class LoginFrame extends JFrame{

private JTextField name;

private JTextField ip;

private JButton ok,cancle;

public Socket socket;

public LoginFrame()

{

super("登录框");

thissetSize(400,80);

thissetLocation(100,100);

name = new JTextField("昵称");

ip = new JTextField("127001");

ok = new JButton("登录");

cancle = new JButton("取消");

okaddActionListener(new listenEvent());

cancleaddActionListener(new listenEvent());

//建立容器

addcomponettocontainer();

thissetDefaultCloseOperation(EXIT_ON_CLOSE);

}

/

建立容器及控件

/

public void addcomponettocontainer()

{

Container c = thisgetContentPane();

csetLayout(null);

namesetBounds(10,10,100,30);

ipsetBounds(120,10,100,30);

oksetBounds(230,10,70,30);

canclesetBounds(310,10,70,30);

cadd(name);

cadd(ip);

cadd(ok);

cadd(cancle);

thissetVisible(true);

thissetResizable(false);

}

public class listenEvent implements ActionListener

{

public void actionPerformed(ActionEvent event) {

// TODO Auto-generated method stub

if(eventgetSource()==ok)

{

String n = namegetText()trim();

String i = ipgetText()trim();

if(""equals(n)||""equals(i))

{

JOptionPaneshowMessageDialog(null,"昵称、IP不能够为空!","错误",JOptionPaneOK_OPTION);

}

else{login(n,i);}

}

if(eventgetSource()==cancle)

{

namesetText("");

ipsetText("");

}

}

}

/

进行登录

@param name

@param ip

/

public void login(String name,String ip)

{

try {

socket = new Socket(ip,7777);

DataOutputStream out = new DataOutputStream(socketgetOutputStream());

outwriteUTF(name);

outflush();//强制输出缓存中的内容

//outclose();

new ClientFrame(name,socket);

destroywindow();

} catch (UnknownHostException e) {

JOptionPaneshowMessageDialog(null,"找不到主机地址(IP错误/网络故障)!","错误",JOptionPaneOK_OPTION);

} catch (IOException e) {

}

}

public void destroywindow()

{

thisdispose();

}

public static void main(String[] args)

{

new LoginFrame();

}

}

==================================================

package server;

import javaawtContainer;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaawteventWindowAdapter;

import javaawteventWindowEvent;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioIOException;

import javanetServerSocket;

import javanetSocket;

import javautilArrayList;

import javautilDate;

import javaxswingJButton;

import javaxswingJFrame;

import javaxswingJOptionPane;

import javaxswingJScrollPane;

import javaxswingJTextArea;

import javaxswingJTextField;

public class ServerFrame extends JFrame{

/

/

private static final long serialVersionUID = 1L;

private JTextArea allmsg;

private JTextField currnum,totalnum,copyright,chatmsg;

private JButton send;

private JScrollPane js;

int num1,num2,port;/ -- num1:当前在线人数 num2:总上线人数 port:服务端口号 --/

private ServerSocket ss;

ArrayList<user> lists;//存放所有在线用户

public ServerFrame()

{

super("聊天室服务器端");

thissetSize(310,660);

thissetLocation(200,50);

lists = new ArrayList<user>();

num1 = num2 =0;

port = 7777;

currnum = new JTextField(" 当前在线人数: "+num1);

currnumsetEnabled(false);

totalnum = new JTextField(" 上线总人数: "+num2);

totalnumsetEnabled(false);

copyright = new JTextField(" ----- all copyright @ TOP-king -----");

copyrightsetEnabled(false);

allmsg = new JTextArea();

allmsgappend(" --------------- 系统消息 --------------\n");

allmsgsetEditable(false);

allmsgsetLineWrap(true); //允许自动换行

js = new JScrollPane(allmsg);//为JTextArea添加滚动条

chatmsg = new JTextField("在此输入系统信息");

chatmsgaddActionListener(new ActionListener(){

@SuppressWarnings("deprecation")

public void actionPerformed(ActionEvent arg0) {

String str = chatmsggetText()trim();

if(!""equals(str))

{sendmsg((new Date())toLocaleString()+" -- 系统消息: "+str);chatmsgsetText("");}

else

JOptionPaneshowMessageDialog(null, "消息不能为空","错误",JOptionPaneOK_OPTION);

chatmsgsetText("");/ -- 发送信息后,将输入栏中的信息清空 -- /

}

});

send = new JButton("发送");

sendaddActionListener(new ActionListener(){

@SuppressWarnings("deprecation")

public void actionPerformed(ActionEvent arg0) {

String str = chatmsggetText()trim();

if(!""equals(str))

{sendmsg((new Date())toLocaleString()+" -- 系统消息: "+str);chatmsgsetText("");}

else

JOptionPaneshowMessageDialog(null, "消息不能为空","错误",JOptionPaneOK_OPTION);

chatmsgsetText("");/ -- 发送信息后,将输入栏中的信息清空 -- /

}

});

//建立容器

addcomponettocontainer();

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we)

{

sendmsg("SYSTEM_CLOSED");/ -- 向客户端发送服务器关闭信息 -- /

destory();

}

});

start(); / -- 启动连接服务 -- /

}

public void addcomponettocontainer()

{

//Container建立容器

Container c = thisgetContentPane();

csetLayout(null);

currnumsetBounds(20,15,130,20);

totalnumsetBounds(155,15,125,20);

jssetBounds(10,50,280,500);

chatmsgsetBounds(10,560,180,30);

sendsetBounds(220,560,70,30);

copyrightsetBounds(10,600,280,20);

cadd(currnum);

cadd(totalnum);

cadd(js);

cadd(chatmsg);

cadd(send);

cadd(copyright);

thissetVisible(true);

thissetResizable(false);

}

/

start()方法监听客户的连接

并且保存客户端的相关信息EG:用户昵称、用户所使用的Socket

用户连接到服务器成功之后,将其保存到用户列表中,并为该用户启动一个线程用于通信 /

@SuppressWarnings("deprecation")

public void start()

{

boolean isStarted = false;/ -- 用于标记服务器是否已经正常启动 -- /

try {

thisss = new ServerSocket(port);

isStarted = true;

thisallmsgappend((new Date())toLocaleString()+" 服务器启动 @ 端口: "+port+"\n");

while(isStarted)

{

Socket client = thisssaccept(); / -- 监听客户端的连接 -- /

DataInputStream in = new DataInputStream(clientgetInputStream());

String name = inreadUTF();

user u = new user();

uname = name;

usocket = client;

listsadd(u); //将该用户加到列表中去

num1++;

num2++;

currnumsetText(" 当前在线人数: "+num1);

totalnumsetText(" 上线总人数: "+num2);

thisallmsgappend((new Date())toLocaleString()+" : "+uname+" 登录 \n");

new Thread(new ClientThread(u))start();/ -- 为该用户启动一个通信线程 -- /

}

} catch (IOException e) {

Systemoutprintln("服务器已经启动");

Systemexit(0);

}

}

/

通信线程主要功能包括:

1监听客户端输入的信息

2将接收到的信息转发给其他用户 /

class ClientThread implements Runnable

{

user user = null;

boolean isConnected = true;

DataInputStream dis = null;

DataOutputStream dos = null;

public ClientThread(user u)

{

thisuser = u;

try {

thisdis = new DataInputStream(thisusersocketgetInputStream());

thisdos = new DataOutputStream(thisusersocketgetOutputStream());

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

public void run()

{

readmsg();

}

/ -- 读取客户的聊天信息 -- /

@SuppressWarnings("deprecation")

public void readmsg()

{

while(isConnected)

{

try {

String msg = disreadUTF();

if("quit&logout"equals(msg))//当用户关闭客户端窗口时,发送quit字符串 表示用户已经退出

{

num1--;

try{

thisdisclose();

thisdosclose();

thisusersocketclose();

thisisConnected = false;

}catch(IOException ioe)

{

ioeprintStackTrace();

}finally{

thisisConnected = false;

if(dis!=null) thisdisclose();

if(dos!=null) thisdosclose();

if(thisusersocket!=null) thisusersocketclose();

}

listsremove(thisuser);//从列表中删除该用户

currnumsetText(" 当前在线人数: "+num1);

allmsgappend((new Date())toLocaleString()+" : "+thisusername+" 退出\n");

}

else

sendmsg(msg);

} catch (IOException e) {

eprintStackTrace();

}

}

}

}

/ -- 将信息进行转发 -- /

public void sendmsg(String msg)

{

user us = new user();

DataOutputStream os = null;

if(listssize()>0)

{

for(int i=0;i<listssize();i++)

{

us = listsget(i);

try {

os = new DataOutputStream(ussocketgetOutputStream());

oswriteUTF(msg);

} catch (IOException e) {

eprintStackTrace();

}

}

}

else

JOptionPaneshowMessageDialog(null, "当前无用户在线。发送消息失败","失败",JOptionPaneOK_OPTION);

}

public void destory()

{

try {

thisssclose();

} catch (IOException e) {

eprintStackTrace();

}

thisdispose();

}

public static void main(String[] args)

{

new ServerFrame();

}

}

=================================================

package server;

import javanet;

public class user {

String name;

Socket socket;

}

CS模式的QQ这是服务器:ChatServerjavaimport javanet;

import javaio;

public class ChatServer

{

final static int thePort=8189;

ServerSocket theServer;

ChatHandler[] chatters;

int numbers=0;

public static void main(String args[])

{

ChatServer app=new ChatServer();

apprun();

}

public ChatServer()

{

try

{

theServer=new ServerSocket(thePort);

chatters=new ChatHandler[10];

}

catch(IOException io){}

}

public void run()

{

try

{

Systemoutprintln("服务器已经建立!");

while(numbers<10)

{

Socket theSocket=theServeraccept();

ChatHandler chatHandler=new ChatHandler(theSocket,this);

chatters[numbers]=chatHandler;

numbers++;

}

}catch(IOException io){}

}

public synchronized void removeConnectionList(ChatHandler c)

{

int index=0;

for(int i=0;i<=numbers-1;i++)

if(chatters[i]==c)index=i;

for(int i=index;i<numbers-1;i++)

chatters[i]=chatters[i+1];

chatters[numbers-1]=null;

numbers--;

}

public synchronized String returnUsernameList()

{

String line="";

for(int i=0;i<=numbers-1;i++)

line=line+chatters[i]user+":";

return line;

}

public void broadcastMessage(String line)

{

Systemoutprintln("发布信息:"+line);

for(int i=0;i<=numbers-1;i++)

chatters[i]sendMessage(line);

}

}====================================================这是客户端:ChatClientjavaimport javaawt;

import javaawtevent;

import javaxswing;

import javanet;

import javaio;

public class ChatClient extends Thread implements ActionListener

{

JTextField messageField,IDField,ipField,portField;

JTextArea message,users;

JButton connect,disconnect;

String user="";

String userList[]=new String[10];

Socket theSocket;

BufferedReader in;

PrintWriter out;

boolean connected=false;

Thread thread;

public static void main(String args[])

{

JFrame frame=new JFrame("聊天室");

framesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

ChatClient cc=new ChatClient();

JPanel content=cccreateComponents();

framegetContentPane()add(content);

framesetSize(550,310);

framesetVisible(true);

}

public JPanel createComponents()

{

JPanel pane=new JPanel(new BorderLayout());

message=new JTextArea(10,35);

messagesetEditable(false);

JPanel paneMsg=new JPanel();

paneMsgsetBorder(BorderFactorycreateTitledBorder("聊天内容"));

paneMsgadd(message);

users=new JTextArea(10,10);

JPanel listPanel=new JPanel();

listPanelsetBorder(BorderFactorycreateTitledBorder("在线用户:"));

listPaneladd(users);

messageField=new JTextField(50);

IDField=new JTextField(5);

ipField=new JTextField("LocalHost");

portField=new JTextField("8189");

connect=new JButton("连 接");

disconnect=new JButton("断 开");

disconnectsetEnabled(false);

JPanel buttonPanel=new JPanel();

buttonPaneladd(new Label("服务器IP:"));

buttonPaneladd(ipField);

buttonPaneladd(new Label("端口:"));buttonPaneladd(portField);

buttonPaneladd(new Label("用户名:"));

buttonPaneladd(IDField);

buttonPaneladd(connect);

buttonPaneladd(disconnect);

paneadd(messageField,"South");

paneadd(buttonPanel,"North");

paneadd(paneMsg,"Center");

paneadd(listPanel,"West");

connectaddActionListener(this);

disconnectaddActionListener(this);

messageFieldaddActionListener(this);

IDFieldaddActionListener(this);

ipFieldaddActionListener(this);

return pane;

}

public void actionPerformed(ActionEvent e)

{

if(egetSource()==connect){

user=IDFieldgetText();

String ip=ipFieldgetText();

int port =IntegerparseInt(portFieldgetText());

if(!userequals("")&&connectToServer(ip,port,user))

{

disconnectsetEnabled(true);

connectsetEnabled(false);

}

}

if(egetSource()==disconnect)disconnectFromServer();

if(egetSource()==messageField)

if(theSocket!=null)

{

outprintln("MESSAGE:"+messageFieldgetText());

messageFieldsetText("");

}

}

public void disconnectFromServer()

{

if(theSocket!=null)

{

try

{

connected=false;

outprintln("LEAVE:"+user);

disconnectsetEnabled(false);

connectsetEnabled(true);

thread=null;

theSocketclose();

}catch(IOException io){}

theSocket=null;

messagesetText("");

userssetText("");

}

}

public boolean connectToServer(String ip,int port,String ID)

{

if(theSocket!=null)

return false;

try

{

theSocket=new Socket(ip,port);

in=new BufferedReader(new InputStreamReader(theSocketgetInputStream()));

out=new PrintWriter(new OutputStreamWriter(theSocketgetOutputStream()),true);

outprintln("USER:"+user);

messagesetText("");

connected=true;

thread=new Thread(this);

threadstart();

}catch(Exception e){return false;}

return true;

}

public void extractMessage(String line)

{

Systemoutprintln(line);

Message messageline;

messageline=new Message(line);

if(messagelineisValid())

{

if(messagelinegetType()equals("JOIN"))

{

user=messagelinegetBody();

messageappend(user+"进入了聊天室\n");

}

else if(messagelinegetType()equals("LIST"))

updateList(messagelinegetBody());

else if(messagelinegetType()equals("MESSAGE"))

messageappend(messagelinegetBody()+"\n");

else if(messagelinegetType()equals("REMOVE"))

messageappend(messagelinegetBody()+"离开了聊天室\n");

}

else

messageappend("出现问题:"+line+"\n");

}

public void updateList(String line)

{

userssetText("");

String str=line;

for(int i=0;i<10;i++)

userList[i]="";

int index=strindexOf(":");

int a=0;

while(index!=-1){

userList[a]=strsubstring(0,index);

str=strsubstring(index+1);

a++;

index=strindexOf(":");

}

for(int i=0;i<10;i++)

usersappend(userList[i]+"\n");

}

public void run(){

try{

String line="";

while(connected && line!=null){

line=inreadLine();

if(line!=null) extractMessage(line);

}

}catch(IOException e){}

}

} =======================================================import javanet;

import javaio;

class ChatHandler extends Thread{

Socket theSocket;

BufferedReader in;

PrintWriter out;

int thePort;

ChatServer parent;

String user="";

boolean disconnect=false;

public ChatHandler(Socket socket,ChatServer parent){

try{

theSocket=socket;

thisparent=parent;

in=new BufferedReader(new InputStreamReader(theSocketgetInputStream()));

out=new PrintWriter(new OutputStreamWriter(theSocketgetOutputStream()),true);

thePort=theSocketgetPort();

start();

}catch(IOException io){}

}

public void sendMessage(String line){

outprintln(line);

}

public void setupUserName(String setname){

user=setname;

//Systemoutprint(user+"参加");

parentbroadcastMessage("JOIN:"+user);

}

public void extractMessage(String line){

Message messageline;

messageline = new Message(line);

if(messagelineisValid()){

if(messagelinegetType()equals("USER")){

setupUserName(messagelinegetBody());

parentbroadcastMessage("LIST:"+parentreturnUsernameList());

}

else if(messagelinegetType()equals("MESSAGE")){

parentbroadcastMessage("MESSAGE:"+user+"说: "+messagelinegetBody());

}

else if(messagelinegetType()equals("LEAVE")){

String c=disconnectClient();

parentbroadcastMessage("REMOVE:"+c);

parentbroadcastMessage("LIST:"+parentreturnUsernameList());

}

}

else

sendMessage("命令不存在!");

}

public String disconnectClient(){

try{

inclose();

outclose();

theSocketclose();

parentremoveConnectionList(this);

disconnect=true;

}catch(Exception ex){}

return user;

}

public void run(){

String line,name;

boolean valid=false;

try{

while((line=inreadLine())!=null){

Systemoutprintln("收到:"+line);

extractMessage(line);

}

}catch(IOException io){}

}

}

=========================================================

Messagejavapublic class Message{

private String type;

private String body;

private boolean valid;

public Message(String messageLine){

valid=false;

type=body=null;

int pos=messageLineindexOf(":");

if(pos>=0){

type=messageLinesubstring(0,pos)toUpperCase();

body=messageLinesubstring(pos+1);

valid=true;

}

}

public Message(String type,String body){

valid=true;

thistype=type;

thisbody=body;

}

public String getType(){

return type;

}

public String getBody(){

return body;

}

public boolean isValid(){

return valid;

}

} ==================================================共有4个文件,先运行服务段端。。。 这是我以前学的时候写过的!希望能帮的上你

以上就是关于求用JAVA做一个聊天机器人全部的内容,包括:求用JAVA做一个聊天机器人、请问能不能帮我写一个Java的聊天窗口文件源代码,不要很复杂,只要能运行,聊天就行了!我用淘宝金币换,谢、JAVA聊天室 客户端 和 服务器 完整代码等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/10067732.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存