JAVA小型聊天室_第1页
JAVA小型聊天室_第2页
JAVA小型聊天室_第3页
JAVA小型聊天室_第4页
JAVA小型聊天室_第5页
已阅读5页,还剩34页未读 继续免费阅读

下载本文档

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

文档简介

1、JAVA小型聊天室下载必读:1、要在工程里新建perties以及perties的配置文件serverhost和serverport分别为服务器所在计算机的IP和端口:perties:serverhost=loaclhostserverport=8088perties:serverhost=loaclhostserverport=80892、 先启动聊天室消息服务器ChatServer和登录服务器LoginServer3、 然后启动登录客户端Login4、 先注册,注册后要重启登录服务器,然后再登录才不会出错(小bug不

2、想修改了,可自行修改)5、 聊天室目前实行了登录界面和聊天界面,可自行开发注册界面等6、 聊天室目前只实现了公聊、私聊、好友列表刷新、上下线提醒等功能。可自行添加其他功能7、 用户信息目前只开发了昵称和密码两个属性,可自行开发其他属性源代码:1、 聊天室消息服务器ChatServer:import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import .InetAddress;import .Serve

3、rSocket;import .Socket;import java.util.HashMap;import java.util.Map;import java.util.Set;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/* * 聊天室消息接收发送服务器 * author Among * */public class ChatServer private ServerSocket server;private Map<String,PrintWriter>PW

4、;/存储每个线程的输出流private Map<String,String>user;/存储每个用户信息private ExecutorService threadPool;/线程池private static final String personalChat="11110001"/私聊标识private static final String publicChat="11110010"/公聊标识private static final String Online="11110011"/上线标识private stati

5、c final String SigningOff="11110100"/下线标识private static final String friendSign="11110101"/好友列表请求标识/* * 构造方法 * 初始化 */public ChatServer()try server=new ServerSocket(8088);/打开新的服务端接口PW=new HashMap<String,PrintWriter>();user=new HashMap<String,String>();threadPool=Execut

6、ors.newFixedThreadPool(50); catch (Exception e) e.printStackTrace();/* * 添加输出流方法,并添加同步互斥锁 * param name * param pw */private synchronized void addPw(String name,PrintWriter pw)PW.put(name,pw);/* * 删除输出流方法,添加同步互斥锁 * param name * param pw */private synchronized void removePw(String name,PrintWriter pw)

7、PW.remove(name, pw);/* * 遍历输出流,群发消息 * 添加同步互斥锁 * param msg */private synchronized void sendMsgtoAll(String msg)Set<String>names=PW.keySet();for(String name:names)PW.get(name).println(msg);/* * 服务器启动方法 * 打开接收器,并把连接进来的socket交给线程开始聊天 */public void start()try while(true)System.out.println("等到客

8、户端连接.");Socket socket=server.accept();System.out.println("一个客户端连接了!");/启动一个线程来处理新连接ClientHandler handler=new ClientHandler(socket);threadPool.execute(handler); catch (Exception e) /* * 线程 * 用于和每个连接进来的socket交互 */class ClientHandler implements Runnableprivate Socket socket;private Strin

9、g host;private int port;private PrintWriter pw=null;private String name;private BufferedReader br;private String Name;/* * 构造方法 * 获取连接进来的socket信息 * param socket */public ClientHandler(Socket socket)InetAddress address=socket.getInetAddress();host=address.getHostAddress();port=socket.getPort();System

10、.out.println(host+port+"上线了。当前在线人数:"+(PW.size()+1);this.socket=socket;/* * 线程run方法 * 获取socket输入输出流 * 1、读取用户名称 * 2、判断消息标识符 * 3、接收并处理消息 * 4、发送消息标识符 * 5、发送消息 */public void run()trypw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),true);br=new BufferedReader(new InputStreamRea

11、der(socket.getInputStream();name=br.readLine();user.put(name, name);addPw(name,pw);String message=null;/sendMsgtoAll(name+"上线了。当前在线人数:"+PW.size();while(message=br.readLine()!=null)if(Online.equals(message)sendMsgtoAll(Online);sendMsgtoAll(name);else if(publicChat.equals(message)message=br.

12、readLine();sendMsgtoAll(publicChat);sendMsgtoAll(name+"说:"+message);System.out.println(name+message);else if(SigningOff.equals(message)/message=br.readLine();/System.out.println(name+message);sendMsgtoAll(SigningOff);sendMsgtoAll(name+"下线了。当前在线人数:"+(PW.size()-1);System.out.printl

13、n(name+"下线了。当前在线人数:"+(PW.size()-1);user.remove(name);/删除下线用户removePw(name,pw);/删除下线用户的输出流socket.close();else if(personalChat.equals(message)message=br.readLine();String msg=message.split(":");PW.get(msg0).println(personalChat);PW.get(msg0).println(name+"悄悄对你说:"+msg1);PW

14、.get(name).println(personalChat);PW.get(name).println("你悄悄对"+msg0+"说:"+msg1);else if(friendSign.equals(message)String msgs=""Set<String>names=user.keySet();for(String n:names)Name=user.get(n);msgs+=Name+":"System.out.println(msgs);sendMsgtoAll(friendSign

15、);sendMsgtoAll(msgs);catch(Exception e)/e.printStackTrace();/*main方法*/public static void main(String args) ChatServer server=new ChatServer();server.start();2、 聊天室登录服务器LoginServer:import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWri

16、ter;import .ServerSocket;import .Socket;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/* * 聊天室登录服务器 * 接收和发送登录注册信息 * author Among * version 1.0

17、*/public class LoginServer private static final String checkLogin="11110110"/检查登录信息标识private static final String Correct="11111111"/信息正确标识private static final String Wrong="00000000"/信息错误标识private static final String Regist="11110111"/注册标识private ServerSocket

18、server;private ExecutorService threadPool;private List<User>user=new ArrayList<User>();private Map<String,String>login;private Save save=new Save();private Iterator<User>it;private User user0=null;/* * 构造方法 * 打开监听接口 * 初始化 */public LoginServer()try server=new ServerSocket(8089

19、);threadPool=Executors.newFixedThreadPool(50);user=save.ReadData();it=user.iterator();login=new HashMap<String,String>();while(it.hasNext()user0=it.next();if(user0=null)continue;login.put(user0.getName(),user0.getPassword(); catch (Exception e) e.printStackTrace();/* * 登录服务器启动方法 * 接收socket连接 *

20、 建立线程处理信息 */public void start()trywhile(true)System.out.println("等待一个登陆客户端.");Socket socket=server.accept();System.out.println("登陆客户端已连接!");threadPool.execute(new LoginHandler(socket);catch(Exception e)e.printStackTrace();/* * 交互信息处理线程 * 1、获取输入输出流 * 2、判断消息标识 * 3、接收消息 * 4、处理消息 * 5

21、、发送消息标识 * 6、发送处理结果 */class LoginHandler implements Runnableprivate Socket socket;public BufferedReader br;public PrintWriter pw;public String logins; public User users;public LoginHandler(Socket socket)this.socket=socket;Override/* * 线程run方法 */public void run() try br=new BufferedReader(new InputStr

22、eamReader(socket.getInputStream(),"utf-8");pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);String message=null;while(message=br.readLine()!=null)System.out.println(message);if(checkLogin.equals(message)message=br.readLine();System.out.println(mes

23、sage);logins=message.split(":");System.out.println(logins0+","+logins1);System.out.println(user.toString();System.out.println();if(logins1.equals(login.get(logins0)pw.println(Correct);elsepw.println(Wrong);else if(Regist.equals(message)message=br.readLine();System.out.println(mes

24、sage); logins=message.split(":");System.out.println(logins0+","+logins1);System.out.println(user.toString();if(login.containsKey(logins0)pw.println(Wrong);elsepw.println(Correct);user.add(new User(logins0,logins1);save.SaveData(user); catch (Exception e) / TODO: handle exception/

25、* * main方法 * param args */public static void main(String args) LoginServer server=new LoginServer();server.start();3、 聊天室登录界面Login:import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.FileInputStream;import jav

26、a.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import .Socket;import java.util.Properties;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import

27、javax.swing.border.TitledBorder;/* * 聊天室登录界面 * 客户端启动处 * author Among * version 1.0 */public class Login implements ActionListenerprivate static final String checkLogin="11110110"/检查登录信息标识private static final String Correct="11111111"/信息正确标识private static final String Regist="

28、;11110111"/注册标识private static Socket socket;private static PrintWriter pw;private static BufferedReader br;private JFrame frame=new JFrame("登录");private JPanel jp1=new JPanel();private JPanel jp2=new JPanel();private JPanel jp3=new JPanel();private JPanel jp4=new JPanel();private JLab

29、el jl1=new JLabel("账号:");private JLabel jl2=new JLabel("密码:");private JTextField jtf1=new JTextField(15);private JTextField jtf2=new JTextField(15);private JButton jb1=new JButton("登录");private JButton jb2=new JButton("注册");SuppressWarnings("unused")

30、private TitledBorder tb=new TitledBorder("");/* * 启动界面方法 */public void init()jb1.addActionListener(this);jb2.addActionListener(this);jp1.add(jl1);jp1.add(jtf1);jp2.add(jl2);jp2.add(jtf2);jp3.add(jb1);jp3.add(jb2);jp4.setLayout(new GridLayout(3,1);jp4.add(jp1);jp4.add(jp2);jp4.add(jp3);fram

31、e.add(jp4);frame.setLocation(532,265);frame.setSize(300, 180);frame.setResizable(false);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);/* * 构造方法 * 读取配置文件 * 和登录服务器建立socket连接 */public Login()try Properties p=new Properties();p.load(new FileInputStream("pertie

32、s");String address=p.getProperty("serverhost");int port=Integer.parseInt(p.getProperty("serverport");socket=new Socket(address,port); catch (Exception e) e.printStackTrace();/* * main方法 * param args */public static void main(String args) Login login=new Login();login.init();

33、/* * Override * 界面监听方法 * 1、获取输入框消息 * 2、判断按钮监听结果 * 3、发送消息标识 * 4、发送消息标识 * 5、接收消息 * 6、判断接收消息 * 7、处理结果 */SuppressWarnings("static-access")public void actionPerformed(ActionEvent e) String ID;String PassWord;if(e.getActionCommand().equals("注册")ID=jtf1.getText();PassWord=jtf2.getText()

34、;if(ID.equals("")JOptionPane.showMessageDialog(null, "请输入账号!");else if(PassWord.equals("")JOptionPane.showMessageDialog(null, "请输入密码!");else trypw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);pw.println(Regist);pw.pr

35、intln(ID+":"+PassWord);br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8");SuppressWarnings("unused")String msg;if(Correct.equals(msg=br.readLine()JOptionPane.showMessageDialog(null, "注册成功!");elseJOptionPane.showMessageDialog(null, &qu

36、ot;账号已存在!");catch(Exception ee)ee.printStackTrace();else if(e.getActionCommand().equals("登录")ID=jtf1.getText();PassWord=jtf2.getText();if(ID.equals("")JOptionPane.showMessageDialog(null, "请输入账号!");else if(PassWord.equals("")JOptionPane.showMessageDialog(n

37、ull, "请输入密码!");else trypw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);pw.println(checkLogin);pw.println(ID+":"+PassWord);br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8");SuppressWarnings("unus

38、ed")String msg;if(Correct.equals(msg=br.readLine()/System.out.println(msg);JOptionPane.showMessageDialog(null, "登录成功!");frame.dispose();ChatSurface CSf=new ChatSurface();/创建聊天界面CSf.user=new User(ID,PassWord);CSf.GetSurface();/打开登录界面CSf.getSocket();/和聊天服务器建立连接else JOptionPane.showMessa

39、geDialog(null, "密码错误,请重新登陆!");catch(Exception ee)4、 聊天室聊天界面ChatSurface:import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowE

40、vent;import java.io.OutputStreamWriter;import java.io.PrintWriter;import javax.swing.DefaultListModel;import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JList;import javax.swing.JPanel;import jav

41、ax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.ListSelectionModel;import javax.swing.ScrollPaneConstants;import javax.swing.border.TitledBorder;/* * 聊天室聊天界面 * author Among * version 1.0 */public class ChatSurface implements ActionListenerprivate st

42、atic final String personalChat="11110001"/私聊标识private static final String publicChat="11110010"/公聊标识private static final String Online="11110011"/上线标识private static final String SigningOff="11110100"/下线标识private static final String friendSign="11110101&qu

43、ot;/好友列表请求标识private JFrame jf=new JFrame("聊天室");private static ChatClient client;private PrintWriter pw;public static User user;public ChatSurface() /设置窗口关闭事件,如果点击窗口右上角叉号关闭,执行下边程序jf.addWindowListener( new WindowAdapter()public void windowClosing(WindowEvent e)try pw=new PrintWriter(client.

44、socket.getOutputStream(),true);pw.println(SigningOff);/发送下线标识pw.println(friendSign);/jf.dispose();/关闭窗口System.exit(0);/退出catch(Exception ex) );public JPanel jp1=new JPanel();public JPanel jp2=new JPanel();public JPanel jp3=new JPanel();public JPanel jp4=new JPanel();public JPanel jp5=new JPanel();pu

45、blic JPanel jp6=new JPanel();public JPanel jp7=new JPanel();public static JTextArea jta1=new JTextArea(12,42);/开辟公聊界面public static JTextArea jta2=new JTextArea(12,42);/开辟私聊界面public JLabel jl1=new JLabel("对");SuppressWarnings("rawtypes")public static JComboBox jcomb=new JComboBox(

46、);public JCheckBox jcb=new JCheckBox("私聊");public JTextField jtf=new JTextField(36);public JButton jb1=new JButton("发送>>");SuppressWarnings("rawtypes")public static DefaultListModel listModel1;SuppressWarnings("rawtypes")public static JList lst1;/* * 获取聊

47、天界面方法 */SuppressWarnings( "unchecked", "rawtypes" )public void GetSurface()jcomb.addItem("所有人");/this.na=name;/this.se=sex;jta1.setEditable(false);jta2.setEditable(false);listModel1= new DefaultListModel();lst1 = new JList(listModel1);lst1.setSelectionMode(ListSelection

48、Model.SINGLE_SELECTION);lst1.setVisibleRowCount(18);lst1.setFixedCellHeight(28);lst1.setFixedCellWidth(100);JScrollPane jsp1=new JScrollPane(jta1);JScrollPane jsp2=new JScrollPane(jta2);JScrollPane jsp3=new JScrollPane(lst1);jsp3.setBorder(new TitledBorder("好友列表");jsp1.setBorder(new Titled

49、Border("主聊天频道");jsp2.setBorder(new TitledBorder("我的频道");jp1.setLayout(new GridLayout(2,1);jp1.add(jsp1);jp1.add(jsp2);jp2.setLayout(new FlowLayout(FlowLayout.LEFT);jp2.add(jl1);jp2.add(jcomb);jp2.add(jcb);jp3.setLayout(new FlowLayout(FlowLayout.LEFT);jp3.add(jtf);jp3.add(jb1);jp4

50、.setLayout(new GridLayout(2,1);jp4.add(jp2);jp4.add(jp3);jp5.setLayout(new BorderLayout();jp5.add(jp1,BorderLayout.NORTH);jp5.add(jp4,BorderLayout.SOUTH);jp6.setLayout(new BorderLayout();jp6.add(jsp3,BorderLayout.NORTH);jp7.setLayout(new FlowLayout(FlowLayout.LEFT);jp7.add(jp5);jp7.add(jp6);jf.add(j

51、p7);jf.setLocation(350,100);jf.setSize(700,650);jf.setResizable(false);jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);jf.setVisible(true);jb1.addActionListener(this);jta1.setLineWrap(true);jta2.setLineWrap(true);jsp1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

52、jsp1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);jsp2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);jsp2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);jsp3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);jsp3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);jf.pack();/* * 获取聊天socket的方法 * 向服务器发送连接消息 */pu

温馨提示

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

评论

0/150

提交评论