java聊天程序源代码.doc_第1页
java聊天程序源代码.doc_第2页
java聊天程序源代码.doc_第3页
java聊天程序源代码.doc_第4页
java聊天程序源代码.doc_第5页
已阅读5页,还剩15页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

java聊天程序源代码服务端:import java.io.*;import .*;import java.util.*;public class ChatServer boolean stat = false; ServerSocket ss = null; List clients = new ArrayList();/用于存客户端 public static void main(String args) new ChatServer().start(); public void start() try ss = new ServerSocket(8888); stat = true; catch(BindException e) /Sever端已经运行,当重复运行时抛异常 System.out.println(端口正在使用中。); System.out.println(请关掉相关程序并重新运行服务器!); /还会抛别的异常,所以直接关闭窗口 System.exit(0); catch(IOException e) e.printStackTrace(); try while(stat) Socket s = ss.accept();System.out.println(a client connected! ); /测试语句写在最左边,以后没用可以删除或注掉 Client c = new Client(s); /每建立一个客户端,就new一个客户端对象,启动一个线程 new Thread(c).start(); clients.add(c); /勿忘写,将每个客户端加入到容器里 catch (IOException e) e.printStackTrace(); finally try ss.close(); catch (IOException e) e.printStackTrace(); class Client implements Runnable private Socket s; private DataInputStream dis; private DataOutputStream dos; private boolean cont = false; public Client(Socket s) this.s = s; try dis = new DataInputStream(s.getInputStream();/初始化 dos = new DataOutputStream(s.getOutputStream(); cont = true; catch (IOException e) e.printStackTrace(); public void send(String str) /用于发送给客户端 try dos.writeUTF(str); catch (IOException e) clients.remove(this); /移除那个退出的对象 System.out.println(一个客户退出了); /e.printStackTrace(); public void run() try while(cont) String str = dis.readUTF(); /阻塞式方法System.out.println(str); for(int i=0; iclients.size(); i+) Client c = clients.get(i); /取客户端 c.send(str); /* 另外两种方法,但不适用,它会锁定服务端 for(Iterator it = clients.iterator(); it.hasNext();) Client c = it.next(); c.send(str); Iterator it = clients.iterator(); while(it.hasNext() Client c = it.next(); c.send(str); */ catch (EOFException e) /readUTF()阻塞式方法,所以关闭客户端会抛异常 System.out.println(Client closed!); catch (IOException e) e.printStackTrace(); finally try if(dis != null) dis.close(); if(dos != null) dos.close(); if(s != null) s.close(); s = null;/更严格的方法,等于空就没人去用了,垃圾收集器就回收走 catch (IOException e) e.printStackTrace(); 客户端:import java.awt.*;import java.awt.event.*;import java.io.*;import .*;public class ChatClient extends Frame Socket s = null; DataOutputStream dos = null; DataInputStream dis = null; private boolean cont = false; TextField tfTxt = new TextField(); TextArea taContent = new TextArea(); Thread tRecv = new Thread(new RecvThread(); public static void main(String args) new ChatClient().launchFrame(); public void launchFrame() setLocation(400, 300); this.setSize(300, 300); add(tfTxt,BorderLayout.SOUTH); add(taContent,BorderLayout.NORTH); pack(); /包在一起,去掉中间空着的 this.addWindowListener(new WindowAdapter() public void windowClosing(WindowEvent e) disconnect(); System.exit(0); ); tfTxt.addActionListener(new TfListent(); setVisible(true); connect(); tRecv.start(); /启动线程 public void connect() try s = new Socket(,8888);/注意不要定义成Socket s,这就成了局部变量而不是成员变量了System.out.println(connected!); dos = new DataOutputStream(s.getOutputStream(); dis = new DataInputStream(s.getInputStream(); cont = true; catch (UnknownHostException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); public void disconnect() try dos.close(); dis.close(); s.close(); catch (IOException e) e.printStackTrace(); /*/无法解决readUTF阻塞式方法 try cont = false; /关闭线程 tRecv.join(); /合并线程,彻底让他停止 catch (InterruptedException e) e.printStackTrace(); finally try dos.close(); /线程停止之后才能关流,不然抛SocketException异常 dis.close(); s.close(); catch (IOException e) e.printStackTrace(); */ private class TfListent implements ActionListener public void actionPerformed(ActionEvent e) String str = tfTxt.getText().trim(); tfTxt.setText(); try dos.writeUTF(str); dos.flush(); catch (IOException e1) e1.printStackTrace(); private class RecvThread implements Runnable public void run() try while(cont) String str = dis.readUTF(); taContent.setText(taContent.getText() + str + n); catch (SocketException e) System.out.println(退出了,bye!); catch (IOException e) e.printStackTrace(); 简单的聊天程序,主要用到的是Socket,线程以及流如果没看懂可以去下载/topics/93279/尚学堂科技_马士兵_在线聊天系统雏形视频教程_java_eclipse.rar 1.客户端package com.client;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import .Socket;import .UnknownHostException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;import com.ui.ChatUI;public class Client extends ChatUI implements ActionListener private String content = ; Socket socket; DateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); public static int i; public Client() super(客户端:); getSendBtn().addActionListener(this); getCancelBtn().addActionListener(this); try +i; socket = new Socket(localhost, 1234); catch (UnknownHostException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); public void actionPerformed(ActionEvent e) if (e.getActionCommand().equals(Send) String msg = getMsgText().getText(); String s = : + df.format(new Date() + n + msg; content = content + s + n; getContentText().setText(content.trim(); getMsgText().setText(); try PrintStream ps = new PrintStream(socket.getOutputStream(); ps.println(msg); catch (UnknownHostException e1) e1.printStackTrace(); catch (IOException e1) e1.printStackTrace(); else if (e.getActionCommand().equals(Cancel) System.exit(0); public static void main(String args) try UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName(); catch (ClassNotFoundException e) e.printStackTrace(); catch (InstantiationException e) e.printStackTrace(); catch (IllegalAccessException e) e.printStackTrace(); catch (UnsupportedLookAndFeelException e) e.printStackTrace(); Client c = new Client(); c.accept(); public void accept() try while (true) BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream(); char msg = new char1024; String msgs = ; while (br.read(msg) != -1) msgs = new String(msg); if (msgs != null) content += : + df.format(new Date() + n + msgs.trim() + n; getContentText().setText(content); catch (IOException e) e.printStackTrace(); 2.服务器端package com.server;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import .ServerSocket;import .Socket;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;import com.client.Client;import com.ui.ChatUI;public class Server extends ChatUI implements ActionListener private String content = ; ServerSocket server; Socket socket; DateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); public Server() super(服务器); getSendBtn().addActionListener(this); getCancelBtn().addActionListener(this); try server = new ServerSocket(1234); while (true) socket = server.accept(); ServerThread s = new ServerThread(socket, getContentText(); new Thread(s).start(); catch (IOException e) e.printStackTrace(); public static void main(String args) try UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName(); catch (ClassNotFoundException e) e.printStackTrace(); catch (InstantiationException e) e.printStackTrace(); catch (IllegalAccessException e) e.printStackTrace(); catch (UnsupportedLookAndFeelException e) e.printStackTrace(); new Server(); / s.accept(); public void actionPerformed(ActionEvent e) if (e.getActionCommand().equals(Send) String msg = getMsgText().getText(); String s = 服务器: + df.format(new Date() + n; content += s + msg + n; getContentText().setText(content); getMsgText().setText(); try PrintStream ps = new PrintStream(socket.getOutputStream(); ps.println(msg); catch (IOException e1) e1.printStackTrace(); else if (e.getActionCommand().equals(Cancel) System.exit(0); public void accept() try while (true) BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream(); char msg = new char1024; String msgs = ; while (br.read(msg) != -1) msgs = new String(msg); if (msgs != null) content += 客户端: + df.format(new Date() + n + msgs.trim() + n; getContentText().setText(content); catch (IOException e) e.printStackTrace(); 3.服务器端线程package com.server;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import .Socket;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.JTextArea;public class ServerThread implements Runnable Socket socket; JTextArea contentText; DateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); String content; public ServerThread(Socket socket, JTextArea contentText) this.socket = socket; this.contentText = contentText; public void run() try while (true) BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream(); char msg = new char1024; String msgs = ; while (br.read(msg) != -1) msgs = new String(msg); if (msgs != null) content += 客户端: + df.format(new Date() + n + msgs.trim() + n; contentText.setText(content); System.out.println(content); catch (IOException e) e.printStackTrace(); 4.界面package com.ui;import java.awt.Adjustable;import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.Point;import java.awt.Rectangle;import java.awt.ScrollPane;import javax.naming.Context;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JViewport;import javax.swing.WindowConstants;public class ChatUI extends JFrame private JTextArea contentText, msgText; private JButton sendBtn, cancelBtn; public ChatUI(String title) super(title); setLayout(new BorderLayout(); setVisible(true); setBounds(250, 150, 530, 450); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); / JPanel conentPanel = new JPanel(); ScrollPane scroll = new ScrollPane(); scroll.setWheelScrollingEnabled(true); scroll.setSize(470, 300); contentText = new JTextArea(12, 40); contentText.setLineWrap(true);/ JViewport jv = new JViewport();/ jv.setViewPosition(new Point(conentPanel.getX(),conentPanel.getY()+500);/ scroll.setViewport(jv); scroll.add(contentText); conentPanel.add(scroll); / JPanel msgPanel = new JPanel(); ScrollPane scrollMsgPanel = new ScrollPane(); scroll.setWheelScrollingEnabled(true); scrollMsgPanel.setSize(470, 70); msgText = new JTextArea(3, 40); msgText.setLineWrap(true); scrollMsgPanel.add(msgText); msgPanel.add(scrollMsgPanel); / JPanel btnPanel = new JPanel(); sendBtn = new JButton(Send); cancelBtn = new JButton(Cancel); btnPanel.add(sendBtn); btnPanel.add(cancelBtn); getContentPane().add(conentPanel, BorderLayout.NORTH); getContentPane().add(msgPanel, BorderLayout.CENTER); getContentPane().add(btnPanel, BorderLayout.SOUTH); public JButton getCancelBtn() return cancelBtn; public void setCancelBtn(JButton cancelBtn) this.cancelBtn = cancelBtn; public JTextArea getContentText() return contentText; public void setContentText(JTextArea contentText) this.contentText = contentText; public JTextArea getMsgText() return msgText; public void setMsgText(JTextArea msgText) this.msgText = msgText; public JButton getSendBtn() return sendBtn; public void setSendBtn(JButton sendBtn) this.sendBtn = sendBtn; Java网络聊天室程序 服务器端:/package chapter1;import .*;import java.io.*;import java.util.*;public class ChatServer /* * param args * m_threads是一个Vector静态变量,维护所有Server方的ServerThread对象, * 通过该变量能向所有加入聊天室的聊天者ChatApplet广播信息,撤销退出的聊天者。 * 聊天服务者ChatServer的主方法。该方法监听聊天者Chat Applet的请求, * 并为新连接的聊天者创建一个服务线程。 */public static void main(String args) / TODO Auto-generated method stub ServerSocket socket=null; Vector m_threads=new Vector(); System.out.println(listen.); try /设置ServerSocket监听端口号为5555,这个数字必须和程序聊天者ChatApplet中的port参数一致 socket=new ServerSocket(5555); catch(Exception e) System.out.println(new ServerSocket() failed!); return; try int nid=0; while(true) /监听是否有新聊天者Chat Applet连接到聊天Server, /线程运行到该语句会封锁,直到有新的连接产生 Socket s=socket.accept(); System.out.println(accepted); /创建一个新的ServerThread ServerThread st=new ServerThread(s,m_threads); /为该线程设置一个ID号 st.setID(nid+); /将线程加入到m_threads Vector中 m_threads.addElement(st); /启动服务线程 new Thread(st).start(); /通知所有ChatApplet有一个新的网友加入 for(int i=0;im_threads.size();i+) ServerThread st1=(ServerThread)m_threads.elementAt(i); st1.write(welcome+st.getID()+to enter chatroom!); System.out.println(Listen again.); catch(Exception e) System.out.println(Server is down.); /监听线程,监听对应的Chat Applet是否有信息传来class ServerThread implements RunnableVector m_threads;Socket m_socket=null;DataInputStream m_in=null;DataOutputStream m_out=null;int m_nid;/初始化线程public ServerThread(Socket s,Vector threads)m_socket=s;m_threads=threads;try/构造数据输入、输出流对象m_in=new DataInputStream(m_socket.getInputStream();m_out=new DataOutputStream(m_socket.getOutputStream();catch(Exception e)public void run() /线程的执行体System.out.println(thread is running);trywhile(true)/监听对应的ChatApplet是否传来消息/线程封锁在m_in.readUTF()中,直到有信息传来才返回String s=m_in.readUTF();if(s=null)break;/如果Chat Applet传来的信息为“leave”,则通知所有其他的ChatApplet自己推出了if(s.trim().equals(leave)for(int i=0;im_threads.size();i+)ServerThread st=(ServerThread)m_threads.elementAt(i);st.write(*+getID()+leave.+*);else/向所有ChatApplet广播该消息for(int i=0;im_threads.size();i+)ServerThread st=(ServerThread)m_threads.elementAt(i);st.write(+s);catch(Exception e)e.printStackTrace();/从m_threads Vector中删除该线程,表示该线程已经离开聊天室m_threads.removeElement(this);trym_socket.close();catch(Exception e) /将msg送回对应的Appletpublic void write(String msg)synchronized(msg)trym_out.writeUTF(msg);catch(IOException e)public int getID() /获得该线程的IDreturn m_nid;public void setID(int nid) /设置线程的IDm_nid=nid;客户端:/package chapter1;import java.awt.*;import java.applet.*;import java.io.*;import .*;/继承Applet,实现Runnablepublic class ChatApplet1 extends Applet implements RunnableTextArea m_textarea; /接受消息显示窗口TextField m_textfield; /发送消息输入窗口DataInp

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论