您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 广告经营 > java聊天程序源代码
java聊天程序源代码服务端:importjava.io.*;importjava.net.*;importjava.util.*;publicclassChatServer{booleanstat=false;ServerSocketss=null;ListClientclients=newArrayListClient();//用于存客户端publicstaticvoidmain(String[]args){newChatServer().start();}publicvoidstart(){try{ss=newServerSocket(8888);stat=true;}catch(BindExceptione){//Sever端已经运行,当重复运行时抛异常System.out.println(端口正在使用中。。。。);System.out.println(请关掉相关程序并重新运行服务器!);//还会抛别的异常,所以直接关闭窗口System.exit(0);}catch(IOExceptione){e.printStackTrace();}try{while(stat){Sockets=ss.accept();System.out.println(aclientconnected!);//测试语句写在最左边,以后没用可以删除或注掉Clientc=newClient(s);//每建立一个客户端,就new一个客户端对象,启动一个线程newThread(c).start();clients.add(c);//勿忘写,将每个客户端加入到容器里}}catch(IOExceptione){e.printStackTrace();}finally{try{ss.close();}catch(IOExceptione){e.printStackTrace();}}}classClientimplementsRunnable{privateSockets;privateDataInputStreamdis;privateDataOutputStreamdos;privatebooleancont=false;publicClient(Sockets){this.s=s;try{dis=newDataInputStream(s.getInputStream());//初始化dos=newDataOutputStream(s.getOutputStream());cont=true;}catch(IOExceptione){e.printStackTrace();}}publicvoidsend(Stringstr){//用于发送给客户端try{dos.writeUTF(str);}catch(IOExceptione){clients.remove(this);//移除那个退出的对象System.out.println(一个客户退出了);//e.printStackTrace();}}publicvoidrun(){try{while(cont){Stringstr=dis.readUTF();//阻塞式方法System.out.println(str);for(inti=0;iclients.size();i++){Clientc=clients.get(i);//取客户端c.send(str);}/*另外两种方法,但不适用,它会锁定服务端for(IteratorClientit=clients.iterator();it.hasNext();){Clientc=it.next();c.send(str);}IteratorClientit=clients.iterator();while(it.hasNext()){Clientc=it.next();c.send(str);}*/}}catch(EOFExceptione){//readUTF()阻塞式方法,所以关闭客户端会抛异常System.out.println(Clientclosed!);}catch(IOExceptione){e.printStackTrace();}finally{try{if(dis!=null)dis.close();if(dos!=null)dos.close();if(s!=null){s.close();s=null;//更严格的方法,等于空就没人去用了,垃圾收集器就回收走}}catch(IOExceptione){e.printStackTrace();}}}}}客户端:importjava.awt.*;importjava.awt.event.*;importjava.io.*;importjava.net.*;publicclassChatClientextendsFrame{Sockets=null;DataOutputStreamdos=null;DataInputStreamdis=null;privatebooleancont=false;TextFieldtfTxt=newTextField();TextAreataContent=newTextArea();ThreadtRecv=newThread(newRecvThread());publicstaticvoidmain(String[]args){newChatClient().launchFrame();}publicvoidlaunchFrame(){setLocation(400,300);this.setSize(300,300);add(tfTxt,BorderLayout.SOUTH);add(taContent,BorderLayout.NORTH);pack();//包在一起,去掉中间空着的this.addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){disconnect();System.exit(0);}});tfTxt.addActionListener(newTfListent());setVisible(true);connect();tRecv.start();//启动线程}publicvoidconnect(){try{s=newSocket(127.0.0.1,8888);//注意不要定义成Sockets,这就成了局部变量而不是成员变量了System.out.println(connected!);dos=newDataOutputStream(s.getOutputStream());dis=newDataInputStream(s.getInputStream());cont=true;}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}publicvoiddisconnect(){try{dos.close();dis.close();s.close();}catch(IOExceptione){e.printStackTrace();}/*//无法解决readUTF阻塞式方法try{cont=false;//关闭线程tRecv.join();//合并线程,彻底让他停止}catch(InterruptedExceptione){e.printStackTrace();}finally{try{dos.close();//线程停止之后才能关流,不然抛SocketException异常dis.close();s.close();}catch(IOExceptione){e.printStackTrace();}}*/}privateclassTfListentimplementsActionListener{publicvoidactionPerformed(ActionEvente){Stringstr=tfTxt.getText().trim();tfTxt.setText();try{dos.writeUTF(str);dos.flush();}catch(IOExceptione1){e1.printStackTrace();}}}privateclassRecvThreadimplementsRunnable{publicvoidrun(){try{while(cont){Stringstr=dis.readUTF();taContent.setText(taContent.getText()+str+'\n');}}catch(SocketExceptione){System.out.println(退出了,bye!);}catch(IOExceptione){e.printStackTrace();}}}}简单的聊天程序,主要用到的是Socket,线程以及流如果没看懂可以去下载尚学堂科技_马士兵_在线聊天系统雏形视频教程_java_eclipse.rar1.客户端packagecom.client;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintStream;importjava.net.Socket;importjava.net.UnknownHostException;importjava.text.DateFormat;importjava.text.SimpleDateFormat;importjava.util.Date;importjavax.swing.UIManager;importjavax.swing.UnsupportedLookAndFeelException;importcom.ui.ChatUI;publicclassClientextendsChatUIimplementsActionListener{privateStringcontent=;Socketsocket;DateFormatdf=newSimpleDateFormat(yyyy-MM-ddHH:mm:ss);publicstaticinti;publicClient(){super(�客户端:);getSendBtn().addActionListener(this);getCancelBtn().addActionListener(this);try{++i;socket=newSocket(localhost,1234);}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}publicvoidactionPerformed(ActionEvente){if(e.getActionCommand().equals(Send)){Stringmsg=getMsgText().getText();Strings=�:+df.format(newDate())+\n+msg;content=content+s+\n;getContentText().setText(content.trim());getMsgText().setText();try{PrintStreamps=newPrintStream(socket.getOutputStream());ps.println
本文标题:java聊天程序源代码
链接地址:https://www.777doc.com/doc-6123940 .html