栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java GUI编程实现在线聊天室

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java GUI编程实现在线聊天室

引言

综合应用Java的GUI编程和网络编程,实现一个能够支持多组用户同时使用的聊天室软件。该聊天室具有比较友好的GUI界面,并使用C/S模式,支持多个用户同时使用,用户可以自己选择加入或者创建房间,和房间内的其他用户互发信息(文字和图片)

主要功能

客户端的功能主要包括如下的功能:

  • 选择连上服务端
  • 显示当前房间列表(包括房间号和房间名称)
  • 选择房间进入
  • 多个用户在线群聊
  • 可以发送表情(用本地的,实际上发送只发送表情的代码)
  • 退出房间
  • 选择创建房间
  • 房间里没人(房主退出),导致房间解散
  • 显示系统提示消息
  • 显示用户消息
  • 构造标准的消息结构发送
  • 维护GUI所需的数据模型

服务端的功能主要包括:

  • 维护用户信息和房间信息
  • 处理用户发送来的消息选择转发或者回复处理结果
  • 构造标准的消息结构发送

架构

整个程序采用C/S设计架构,分为一个服务端和多个客户端。服务端开放一个端口给所有开客户端,客户端连接该端口并收发信息,服务端在内部维护客户端的组,并对每一个客户端都用一个子线程来收发信息

基本类的设计

User类

package User;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


public class User {
 private String name;
 private long id;
 private long roomId;
 private Socket socket;
 private BufferedReader br;
 private PrintWriter pw;

 
 public User(String name, long id, final Socket socket) throws IOException {
  this.name=name;
  this.id=id;
  this.socket=socket;
  this.br=new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
  this.pw=new PrintWriter(socket.getOutputStream());

 }

 
 public long getId() {
  return id;
 }

 
 public void setId(long id) {
  this.id = id;
 }

 
 public long getRoomId() {
  return roomId;
 }

 
 public void setRoomId(long roomId) {
  this.roomId = roomId;
 }

 
 public void setName(String name) {
  this.name = name;
 }

 
 public String getName() {
  return name;
 }

 
 public Socket getSocket() {
  return socket;
 }

 
 public void setSocket(Socket socket) {
  this.socket = socket;
 }

 
 public BufferedReader getBr() {
  return br;
 }

 
 public void setBr(BufferedReader br) {
  this.br = br;
 }

 
 public PrintWriter getPw() {
  return pw;
 }

 
 public void setPw(PrintWriter pw) {
  this.pw = pw;
 }

 
 @Override
 public String toString() {
  return "#User"+id+"#"+name+"[#Room"+roomId+"#]";
 }
}

Room类

package Room;

import java.util.ArrayList;
import java.util.List;

import User.User;


public class Room {
 private String name;
 private long roomId;
 private ArrayList list;
 private int totalUsers;

 
 public String getName() {
  return name;
 }

 
 public void setName(String name) {
  this.name = name;
 }

 
 public long getRoomId() {
  return roomId;
 }

 
 public void setRoomId(long roomId) {
  this.roomId = roomId;
 }

 
 public void addUser(User user) {
  if(!list.contains(user)){
   list.add(user);
   totalUsers++;
  }else{
   System.out.println("User is already in Room<"+name+">:"+user);
  }
 }

 
 public int delUser(User user){
  if(list.contains(user)){
   list.remove(user);
   return --totalUsers;
  }else{
   System.out.println("User is not in Room<"+name+">:"+user);
   return totalUsers;
  }
 }

 
 public ArrayList getUsers(){
  return list;
 }

 
 public String[] getUserNames(){
  String[] userList = new String[list.size()];
  int i=0;
  for(User each: list){
   userList[i++]=each.getName();
  }
  return userList;
 }

 
 public Room(String name, long roomId) {
  this.name=name;
  this.roomId=roomId;
  this.totalUsers=0;
  list = new ArrayList<>();
 }
}

RoomList类

package Room;

import java.awt.image.DirectColorModel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import User.User;


public class RoomList {
 private HashMap map;
 private long unusedRoomId;
 public static long MAX_ROOMS = 9999;
 private int totalRooms;

 
 public RoomList(){
  map = new HashMap<>();
  unusedRoomId = 1;
  totalRooms = 0;
 }

 
 public long createRoom(String name){
  if(totalRooms> set = map.entrySet();
  Iterator> iterator = set.iterator();
  while(iterator.hasNext()){
   Map.Entry entry = iterator.next();
   long key = entry.getKey();
   Room value = entry.getValue();
   strings[i][0]=""+key;
   strings[i][1]=value.getName();
  }
  return strings;
 }

 
 public Room getRoom(long roomID){
  if(map.containsKey(roomID)){
   return map.get(roomID);
  }
  else 
   return null;
 }
}

服务端

Server

package Server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.*;

import Room.Room;
import Room.RoomList;
import User.User;

public class Server {
 private ArrayList allUsers;
 private RoomList rooms;
 private int port;
 private ServerSocket ss;
 private long unusedUserID;
 public final long MAX_USERS = 999999;

 
 public Server(int port) throws Exception {
  allUsers = new ArrayList<>();
  rooms = new RoomList();
  this.port=port;
  unusedUserID=1;
  ss = new ServerSocket(port);
  System.out.println("Server is builded!");
 }

 
 private long getNextUserID(){
  if(unusedUserID < MAX_USERS)
   return unusedUserID++;
  else
   return -1;
 }

 
 public void startListen() throws Exception{
  while(true){
   Socket socket = ss.accept();
   long id = getNextUserID();
   if(id != -1){
    User user = new User("User"+id, id, socket);
    System.out.println(user.getName() + " is login...");
    allUsers.add(user);
    ServerThread thread = new ServerThread(user, allUsers, rooms);
    thread.start();
   }else{
    System.out.println("Server is full!");
    socket.close();
   }
  }
 }

 
 public static void main(String[] args) {
  try {
   Server server = new Server(9999);
   server.startListen();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

ServerThread

package Server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Room.Room;
import Room.RoomList;
import User.User;


public class ServerThread extends Thread {
 private User user;
 private ArrayList userList;
 private RoomList map;   
 private long roomId;
 private PrintWriter pw;
 
 public ServerThread(User user, 
   ArrayList userList, RoomList map){
  this.user=user;
  this.userList=userList;
  this.map=map;
  pw=null;
  roomId = -1;
 }

 
 public void run(){
  try{
   while (true) {
    String msg=user.getBr().readLine();
    System.out.println(msg); 
    parseMsg(msg);
   }
  }catch (SocketException se) { 
   System.out.println("user "+user.getName()+" logout.");

  }catch (Exception e) { 
   e.printStackTrace();
  }finally {
   try {
    
    remove(user);
    user.getBr().close();
    user.getSocket().close();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
  }
 }

 
 private void parseMsg(String msg){
  String code = null;
  String message=null;
  if(msg.length()>0){
   
   Pattern pattern = Pattern.compile("(.*)");
   Matcher matcher = pattern.matcher(msg);
   if(matcher.find()){
    code = matcher.group(1);
   }
   
   pattern = Pattern.compile("(.*)");
   matcher = pattern.matcher(msg);
   if(matcher.find()){
    message = matcher.group(1);
   }

   switch (code) {
   case "join":
    // add to the room
    // code = 1, 直接显示在textarea中
    // code = 11, 在list中加入
    // code = 21, 把当前房间里的所有用户返回给client
    if(roomId == -1){
     roomId = Long.parseLong(message);
     map.join(user, roomId);
     sendRoomMsgExceptSelf(buildCodeWithMsg(""+user.getName()+""+user.getId()+"", 11));
     // 这个消息需要加入房间里已有用户的列表
     returnMsg(buildCodeWithMsg("你加入了房间:" + map.getRoom(roomId).getName(), 1));
     returnMsg(buildCodeWithMsg(getMembersInRoom(), 21));
    }else{
     map.esc(user, roomId);
     sendRoomMsg(buildCodeWithMsg(""+user.getId(), 12));
     long oldRoomId = roomId;
     roomId = Long.parseLong(message);
     map.join(user, roomId);
     sendRoomMsgExceptSelf(buildCodeWithMsg(""+user.getName()+""+user.getId()+"", 11));
     returnMsg(buildCodeWithMsg("你退出房间:" + map.getRoom(oldRoomId).getName() + ",并加入了房间:" + roomId,1));
     returnMsg(buildCodeWithMsg(getMembersInRoom(), 21));
    }
    break;
   case "esc":
    // delete from room list
    // code = 2, 弹窗提示
    // code = 12, 对所有该房间的其他用户发送该用户退出房间的信息,从list中删除
    if(roomId!=-1){
     int flag=map.esc(user, roomId);
     sendRoomMsgExceptSelf(buildCodeWithMsg(""+user.getId(), 12));
     long oldRoomId=roomId;
     roomId = -1;
     returnMsg(buildCodeWithMsg("你已经成功退出房间,不会收到消息", 2));
     if(flag==0){
      sendMsg(buildCodeWithMsg(""+oldRoomId, 13));
     }
    }else{
     returnMsg(buildCodeWithMsg("你尚未加入任何房间", 2));
    }
    break;
   case "list":
    // list all the rooms
    // code = 3, 在客户端解析rooms,并填充roomlist
    returnMsg(buildCodeWithMsg(getRoomsList(), 3));
    break;
   case "message":
    // send message
    // code = 4, 自己收到的话,打印的是‘你说:....'否则打印user id对应的name
    sendRoomMsg(buildCodeWithMsg(""+user.getId()+""+message+"", 4));
    break;
   case "create":
    // create a room 
    // code=5,提示用户进入了房间
    // code=15,需要在其他所有用户的room列表中更新
    roomId = map.createRoom(message);
    map.join(user, roomId);
    sendMsg(buildCodeWithMsg(""+roomId+""+message+"", 15));
    returnMsg(buildCodeWithMsg("你进入了创建的房间:"+map.getRoom(roomId).getName(), 5));
    returnMsg(buildCodeWithMsg(getMembersInRoom(), 21));
    break;
   case "setname":
    // set name for user
    // code=16,告诉房间里的其他人,你改了昵称
    user.setName(message);
    sendRoomMsg(buildCodeWithMsg(""+user.getId()+""+message+"", 16));
    break;
   default:
    // returnMsg("something unknown");
    System.out.println("not valid message from user"+user.getId());
    break;
   }
  } 
 }

 
 private String getMembersInRoom(){
  
  Room room = map.getRoom(roomId);
  StringBuffer stringBuffer = new StringBuffer();
  if(room != null){
   
   ArrayList users = room.getUsers();
   for(User each: users){
    stringBuffer.append(""+each.getName()+
 ""+each.getId()+"");
   }
  }
  return stringBuffer.toString();
 }

 
 private String getRoomsList(){
  String[][] strings = map.listRooms();
  StringBuffer sb = new StringBuffer();
  for(int i=0; i"+strings[i][1]+
      ""+strings[i][0]+"");
  }
  return sb.toString();
 }

 
 private String buildCodeWithMsg(String msg, int code){
  return ""+code+""+msg+"n";
 }

 
 private void sendMsg(String msg) {
//  System.out.println("In sendMsg()");
  
  for(User each:userList){
   try {
    pw=each.getPw();
    pw.println(msg);
    pw.flush();
    System.out.println(msg);
   } catch (Exception e) {
    System.out.println("exception in sendMsg()");
   }
  }
 }

 
 private void sendRoomMsg(String msg){
  
  Room room = map.getRoom(roomId);
  if(room != null){
   ArrayList users = room.getUsers();
   for(User each: users){
    pw = each.getPw();
    pw.println(msg);
    pw.flush();
   }
  }
 }
 
 private void sendRoomMsgExceptSelf(String msg){
  Room room = map.getRoom(roomId);
  if(room != null){
   ArrayList users = room.getUsers();
   for(User each: users){
    if(each.getId()!=user.getId()){
     pw = each.getPw();
     pw.println(msg);
     pw.flush();
    }
   }
  }
 }

 
 private void returnMsg(String msg){
  try{
   pw = user.getPw();
   pw.println(msg);
   pw.flush();
  }catch (Exception e) {
   System.out.println("exception in returnMsg()");
  }
 }

 
 private void remove(User user){
  if(roomId!=-1){
   int flag=map.esc(user, roomId);
   sendRoomMsgExceptSelf(buildCodeWithMsg(""+user.getId(), 12));
   long oldRoomId=roomId;
   roomId = -1;
   if(flag==0){
    sendMsg(buildCodeWithMsg(""+oldRoomId, 13));
   }
  }
  userList.remove(user);
 }
}

客户端

Client

package Client;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.Jframe;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.Styleddocument;



public class Client implements ActionListener{
 private Jframe frame;
 private Socket socket;
 private BufferedReader br;
 private PrintWriter pw;
 private String name;
 private HashMap rooms_map;
 private HashMap users_map;
 private JTextField host_textfield;
 private JTextField port_textfield;
 private JTextField text_field;
 private JTextField name_textfiled;
 private JLabel rooms_label;
 private JLabel users_label;
 private JList roomlist;
 private JList userlist;
 private JTextPane msgArea;
 private JScrollPane textScrollPane;
 private JScrollBar vertical;
 DefaultListModel rooms_model;
 DefaultListModel users_model;

 
 public Client(){
  rooms_map = new HashMap<>();
  users_map = new HashMap<>();
  initialize();
 }

 
 public boolean connect(String host, int port){
  try {
   socket = new Socket(host, port);
   System.out.println("Connected to server!"+socket.getRemoteSocketAddress());
   br=new BufferedReader(new InputStreamReader(System.in));
   pw=new PrintWriter(socket.getOutputStream());
   
   ClientThread thread = new ClientThread(socket, this);
   thread.start();

   return true;

  } catch (IOException e) {
   System.out.println("Server error");
   JOptionPane.showMessageDialog(frame, "服务器无法连接!");
   return false;
  }
 }

 
// public void sendMsg(){
//  String msg;
//  try {
//   while(true){
//    msg = br.readLine();
//    pw.println(msg);
//    pw.flush();
//   }
//  } catch (IOException e) {
//   System.out.println("error when read msg and to send.");
//  }
// }

 
 public void sendMsg(String msg, String code){
  try {
   pw.println(""+code+""+msg+"");
   pw.flush();
  } catch (Exception e) {
   //一般是没有连接的问题
   System.out.println("error in sendMsg()");
   JOptionPane.showMessageDialog(frame, "请先连接服务器!");
  }
 }

 
 private void initialize() {
  
  setUIStyle();
  setUIFont();

  Jframe frame = new Jframe("ChatOnline");
  JPanel panel = new JPanel();  
  JPanel headpanel = new JPanel(); 
  JPanel footpanel = new JPanel(); 
  JPanel leftpanel = new JPanel(); 
  JPanel rightpanel = new JPanel(); 

  
  BorderLayout layout = new BorderLayout();
  
  GridBagLayout gridBagLayout = new GridBagLayout();
  
  FlowLayout flowLayout = new FlowLayout();
  
  frame.setBounds(100, 100, 800, 600);
  frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
  frame.setContentPane(panel);
  frame.setLayout(layout);
  
  headpanel.setLayout(flowLayout);
  footpanel.setLayout(gridBagLayout);
  leftpanel.setLayout(gridBagLayout);
  rightpanel.setLayout(gridBagLayout);
  leftpanel.setPreferredSize(new Dimension(130, 0));
  rightpanel.setPreferredSize(new Dimension(130, 0));


  
  host_textfield = new JTextField("127.0.0.1");
  port_textfield = new JTextField("9999");
  name_textfiled = new JTextField("匿名");
  host_textfield.setPreferredSize(new Dimension(100, 25));
  port_textfield.setPreferredSize(new Dimension(70, 25));
  name_textfiled.setPreferredSize(new Dimension(150, 25));

  JLabel host_label = new JLabel("服务器IP");
  JLabel port_label = new JLabel("端口");
  JLabel name_label = new JLabel("昵称");

  JButton head_connect = new JButton("连接");
//  JButton head_change = new JButton("确认更改");
  JButton head_create = new JButton("创建房间");

  headpanel.add(host_label);
  headpanel.add(host_textfield);
  headpanel.add(port_label);
  headpanel.add(port_textfield);
  headpanel.add(head_connect);
  headpanel.add(name_label);
  headpanel.add(name_textfiled);
//  headpanel.add(head_change);
  headpanel.add(head_create);

  
  JButton foot_emoji = new JButton("表情");
  JButton foot_send = new JButton("发送");
  text_field = new JTextField();
  footpanel.add(text_field, new GridBagConstraints(0, 0, 1, 1, 100, 100, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  footpanel.add(foot_emoji, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  footpanel.add(foot_send, new GridBagConstraints(2, 0, 1, 1, 1.0, 1.0, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

  
  rooms_label = new JLabel("当前房间数:0");
  users_label = new JLabel("房间内人数:0");
  JButton join_button = new JButton("加入房间");
  JButton esc_button = new JButton("退出房间");

  rooms_model = new DefaultListModel<>();
  users_model = new DefaultListModel<>();
//  rooms_model.addElement("房间1");
//  rooms_model.addElement("房间2");
//  rooms_model.addElement("房间3");
//  String fangjian = "房间1";
//  rooms_map.put(fangjian, 1);

  roomlist = new JList<>(rooms_model);
  userlist = new JList<>(users_model);

  JScrollPane roomListPane = new JScrollPane(roomlist);
  JScrollPane userListPane = new JScrollPane(userlist);

  leftpanel.add(rooms_label, new GridBagConstraints(0, 0, 1, 1, 1, 1, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  leftpanel.add(join_button, new GridBagConstraints(0, 1, 1, 1, 1, 1, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  leftpanel.add(esc_button, new GridBagConstraints(0, 2, 1, 1, 1, 1, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  leftpanel.add(roomListPane, new GridBagConstraints(0, 3, 1, 1, 100, 100, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  rightpanel.add(users_label, new GridBagConstraints(0, 0, 1, 1, 1, 1, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  rightpanel.add(userListPane,new GridBagConstraints(0, 1, 1, 1, 100, 100, 
    GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

  
  msgArea = new JTextPane();
  msgArea.setEditable(false);
  textScrollPane = new JScrollPane();
  textScrollPane.setViewportView(msgArea);
  vertical = new JScrollBar(JScrollBar.VERTICAL);
  vertical.setAutoscrolls(true);
  textScrollPane.setVerticalScrollBar(vertical);

  
  panel.add(headpanel, "North");
  panel.add(footpanel, "South");
  panel.add(leftpanel, "West");
  panel.add(rightpanel, "East");
  panel.add(textScrollPane, "Center");

  
  
  head_connect.addActionListener(this);
  
  foot_send.addActionListener(this);
  
//  head_change.addActionListener(this);
  
  head_create.addActionListener(this);
  
  foot_emoji.addActionListener(this);
  
  join_button.addActionListener(this);
  
  esc_button.addActionListener(this);

  
  frame.setVisible(true);
 }

 
 @Override
 public void actionPerformed(ActionEvent e) {
  String cmd = e.getActionCommand();
  switch (cmd) {
  case "连接": 
   String strhost = host_textfield.getText();
   String strport = port_textfield.getText();
   connect(strhost, Integer.parseInt(strport));
   String nameSeted = JOptionPane.showInputDialog("请输入你的昵称:"); 
   name_textfiled.setText(nameSeted);
   name_textfiled.setEditable(false);
   port_textfield.setEditable(false);
   host_textfield.setEditable(false);
   
   sendMsg(nameSeted, "setname");
   sendMsg("", "list");
   break;
//  case "确认更改":
//   String strname = name_textfiled.getText();
//   name = strname;
//   sendMsg(strname, "setname");
//   break;
  case "加入房间": 
   String selected = roomlist.getSelectedValue();
   if(rooms_map.containsKey(selected)){
    sendMsg(""+rooms_map.get(selected), "join");
   }
   break;
  case "退出房间": 
   sendMsg("", "esc");
   break;
  case "发送":  
   String text = text_field.getText();
   text_field.setText("");
   sendMsg(text, "message");
   break;
  case "表情":  
   IconDialog dialog = new IconDialog(frame, this);
   break;
  case "创建房间": 
   String string = JOptionPane.showInputDialog("请输入你的房间名称");
   if(string==null || string.equals("")){
    string = name+(int)(Math.random()*10000)+"的房间";
   }
   sendMsg(string, "create");
   break;
  default:
   break;
  }

 }


 

 
 public void addUser(String content){
  if(content.length()>0){
   Pattern pattern = Pattern.compile("(.*)(.*)");
   Matcher matcher = pattern.matcher(content);
   if(matcher.find()){
    
    String name = matcher.group(1);
    String id = matcher.group(2);
    insertUser(Integer.parseInt(id), name);
    insertMessage(textScrollPane, msgArea, null, "系统:", name+"加入了聊天室");
   }
  }
  users_label.setText("房间内人数:"+users_map.size()); 
 }

 
 public void delUser(String content){
  if(content.length()>0){
   int id = Integer.parseInt(content);
   
   Set set = users_map.keySet();
   Iterator iter = set.iterator();
   String name=null;
   while(iter.hasNext()){
    name = iter.next();
    if(users_map.get(name)==id){
     users_model.removeElement(name);
     break;
    }
   }
   users_map.remove(name);
   insertMessage(textScrollPane, msgArea, null, "系统:", name+"退出了聊天室");
  }
  users_label.setText("房间内人数:"+users_map.size());
 }


 
 public void updateUser(String content){
  if(content.length()>0){
   Pattern pattern = Pattern.compile("(.*)(.*)");
   Matcher matcher = pattern.matcher(content);
   if(matcher.find()){
    String id = matcher.group(1);
    String name = matcher.group(2);
    insertUser(Integer.parseInt(id), name);
   }
  }
 }

 
 public void listUsers(String content){
  String name = null;
  String id=null;
  Pattern rough_pattern=null;
  Matcher rough_matcher=null;
  Pattern detail_pattern=null;
  
  if(content.length()>0){
   rough_pattern = Pattern.compile("(.*?)");
   rough_matcher = rough_pattern.matcher(content);
   while(rough_matcher.find()){
    String detail = rough_matcher.group(1);
    detail_pattern = Pattern.compile("(.*)(.*)");
    Matcher detail_matcher = detail_pattern.matcher(detail);
    if(detail_matcher.find()){
     name = detail_matcher.group(1);
     id = detail_matcher.group(2);
     insertUser(Integer.parseInt(id), name);
    }
   }
  }
  users_label.setText("房间内人数:"+users_map.size());
 }

 
 public void updatetextarea(String content){
  insertMessage(textScrollPane, msgArea, null, "系统:", content);
 }

 
 public void updatetextareaFromUser(String content){
  if(content.length()>0){
   Pattern pattern = Pattern.compile("(.*)(.*)");
   Matcher matcher = pattern.matcher(content);
   if(matcher.find()){
    String from = matcher.group(1);
    String smsg = matcher.group(2);
    String fromName = getUserName(from);
    if(fromName.equals(name))
     fromName = "你";
    if(smsg.startsWith("")){
     String emojiCode = smsg.substring(7, smsg.length()-8);
//     System.out.println(emojiCode);
     insertMessage(textScrollPane, msgArea, emojiCode, fromName+"说:", null);
     return ;
    }
    insertMessage(textScrollPane, msgArea, null, fromName+"说:", smsg);
   }
  }
 }

 
 public void showEscDialog(String content){
  JOptionPane.showMessageDialog(frame, content);
  
  msgArea.setText("");
  users_model.clear();
  users_map.clear();
  users_label.setText("房间内人数:0");

 }
 
 public void addRoom(String content){
  if(content.length()>0){
   Pattern pattern = Pattern.compile("(.*)(.*)");
   Matcher matcher = pattern.matcher(content);
   if(matcher.find()){
    String rid = matcher.group(1);
    String rname = matcher.group(2);
    insertRoom(Integer.parseInt(rid), rname);
   }
  }
  rooms_label.setText("当前房间数:"+rooms_map.size());
 }

 
 public void delRoom(String content){
  if(content.length()>0){
   int delRoomId = Integer.parseInt(content);

   Set set = rooms_map.keySet();
   Iterator iter = set.iterator();
   String rname=null;
   while(iter.hasNext()){
    rname = iter.next();
    if(rooms_map.get(rname)==delRoomId){
     rooms_model.removeElement(rname);
     break;
    }
   }
   rooms_map.remove(rname);
  }
  rooms_label.setText("当前房间数:"+rooms_map.size());
 }

 
 public void listRooms(String content){
  String rname = null;
  String rid=null;
  Pattern rough_pattern=null;
  Matcher rough_matcher=null;
  Pattern detail_pattern=null;
  if(content.length()>0){
   rough_pattern = Pattern.compile("(.*?)");
   rough_matcher = rough_pattern.matcher(content);
   while(rough_matcher.find()){
    String detail = rough_matcher.group(1);
    detail_pattern = Pattern.compile("(.*)(.*)");
    Matcher detail_matcher = detail_pattern.matcher(detail);
    if(detail_matcher.find()){
     rname = detail_matcher.group(1);
     rid = detail_matcher.group(2);
     insertRoom(Integer.parseInt(rid), rname);
    }
   }
  }
  rooms_label.setText("当前房间数:"+rooms_map.size());
 }
 
 private void insertRoom(Integer rid, String rname){
  if(!rooms_map.containsKey(rname)){
   rooms_map.put(rname, rid);
   rooms_model.addElement(rname);
  }else{
   rooms_map.remove(rname);
   rooms_model.removeElement(rname);
   rooms_map.put(rname, rid);
   rooms_model.addElement(rname);
  }
  rooms_label.setText("当前房间数:"+rooms_map.size());
 }
 
 private void insertUser(Integer id, String name){
  if(!users_map.containsKey(name)){
   users_map.put(name, id);
   users_model.addElement(name);
  }else{
   users_map.remove(name);
   users_model.removeElement(name);
   users_map.put(name, id);
   users_model.addElement(name);
  }
  users_label.setText("房间内人数:"+users_map.size());
 }

 
 private String getUserName(String strId){
  int uid = Integer.parseInt(strId);
  Set set = users_map.keySet();
  Iterator iterator = set.iterator();
  String cur=null;
  while(iterator.hasNext()){
   cur = iterator.next();
   if(users_map.get(cur)==uid){
    return cur;
   }
  }
  return "";
 }

 
 private String getRoomName(String strId){
  int rid = Integer.parseInt(strId);
  Set set = rooms_map.keySet();
  Iterator iterator = set.iterator();
  String cur = null;
  while(iterator.hasNext()){
   cur = iterator.next();
   if(rooms_map.get(cur)==rid){
    return cur;
   }
  }
  return "";
 }

 
 private void insertMessage(JScrollPane scrollPane, JTextPane textPane,
   String icon_code, String title, String content){
  Styleddocument document = textPane.getStyleddocument();  
  
  SimpleAttributeSet title_attr = new SimpleAttributeSet();
  StyleConstants.setBold(title_attr, true);
  StyleConstants.setForeground(title_attr, Color.BLUE);
  
  SimpleAttributeSet content_attr = new SimpleAttributeSet(); 
  StyleConstants.setBold(content_attr, false); 
  StyleConstants.setForeground(content_attr, Color.BLACK);
  Style style = null;
  if(icon_code!=null){
   Icon icon = new ImageIcon("icon/"+icon_code+".png");
   style = document.addStyle("icon", null); 
   StyleConstants.setIcon(style, icon);
  }

  try { 
   document.insertString(document.getLength(), title+"n", title_attr);
   if(style!=null)
    document.insertString(document.getLength(), "n", style);
   else
    document.insertString(document.getLength(), " "+content+"n", content_attr);

  } catch (BadLocationException ex) { 
   System.out.println("Bad location exception");
  }
  
  vertical.setValue(vertical.getMaximum());
 }

 
 public static void setUIFont()
 {
  Font f = new Font("微软雅黑", Font.PLAIN, 14);
  String names[]={ "Label", "CheckBox", "PopupMenu","MenuItem", "CheckBoxMenuItem",
    "JRadioButtonMenuItem","ComboBox", "Button", "Tree", "ScrollPane",
    "TabbedPane", "EditorPane", "TitledBorder", "Menu", "textarea","TextPane",
    "OptionPane", "MenuBar", "ToolBar", "ToggleButton", "ToolTip",
    "ProgressBar", "TableHeader", "Panel", "List", "ColorChooser",
    "PasswordField","TextField", "Table", "Label", "Viewport",
    "RadioButtonMenuItem","RadioButton", "DesktopPane", "Internalframe"
  }; 
  for (String item : names) {
    UIManager.put(item+ ".font",f); 
  }
 }
 
 public static void setUIStyle(){
  String lookAndFeel =UIManager.getSystemLookAndFeelClassName();
  try {
   UIManager.setLookAndFeel(lookAndFeel);
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InstantiationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (UnsupportedLookAndFeelException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 
 public static void main(String[] args) {
  Client client = new Client();
 }


}

ClientThread

package Client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ClientThread extends Thread{
 private Socket socket;
 private Client client;
 private BufferedReader br;
 private PrintWriter pw;
 
 public ClientThread(Socket socket, Client client){
  this.client = client;
  this.socket = socket;
  try {
   br=new BufferedReader(new InputStreamReader(socket.getInputStream()));

  } catch (IOException e) {
   System.out.println("cannot get inputstream from socket.");
  }
 }

 
 public void run() {
  try{
   br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
   while(true){
    String msg = br.readLine();
    parseMessage(msg);
   }
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public void parseMessage(String message){
  String code = null;
  String msg=null;
  
  if(message.length()>0){
   Pattern pattern = Pattern.compile("(.*)");
   Matcher matcher = pattern.matcher(message);
   if(matcher.find()){
    code = matcher.group(1);
   }
   pattern = Pattern.compile("(.*)");
   matcher = pattern.matcher(message);
   if(matcher.find()){
    msg = matcher.group(1);
   }
   System.out.println(code+":"+msg);
   switch(code){
   case "1": 
    client.updatetextarea(msg);
    break;
   case "2": 
    client.showEscDialog(msg);
    break;
   case "3": 
    client.listRooms(msg);
    break;
   case "4": 
    client.updatetextareaFromUser(msg);
    break;
   case "5": 
    client.updatetextarea(msg);
    break;
   case "11": 
    client.addUser(msg);
    break;
   case "12": 
    client.delUser(msg);
    break;
   case "13": 
    client.delRoom(msg);
    break;
   case "15": 
    client.addRoom(msg);
    break;
   case "16": 
    client.updateUser(msg);
    break;
   case "21": 
    client.listUsers(msg);
    break;
   }
  }

 }
}

IconDialog(选择表情界面)

package Client;

import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.Jframe;

public class IconDialog implements ActionListener {

 private JDialog dialog;
 private Client client;
 
 public IconDialog(Jframe frame, Client client) {
  this.client = client;
  dialog = new JDialog(frame, "请选择表情", true);
  
  JButton[] icon_button = new JButton[16];
  ImageIcon[] icons = new ImageIcon[16];
  
  Container dialogPane = dialog.getContentPane();
  dialogPane.setLayout(new GridLayout(0, 4));
  
  for(int i=1; i<=15; i++){
   icons[i] = new ImageIcon("icon/"+i+".png");
   icons[i].setImage(icons[i].getImage().getScaledInstance(50, 50, Image.SCALE_DEFAULT));
   icon_button[i] = new JButton(""+i, icons[i]);
   icon_button[i].addActionListener(this);
   dialogPane.add(icon_button[i]);
  }
  dialog.setBounds(200,266,266,280);
  dialog.show();
 }

 @Override
 public void actionPerformed(ActionEvent e) {
  
  String cmd = e.getActionCommand();
  System.out.println(cmd);
  dialog.dispose();
  client.sendMsg(""+cmd+"", "message");
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140384.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号