基于java网络聊天室--客户端

ChatClient.java
包含名为ChatClient的public类,其主要功能为定义客户端的界面,添加时间监听与事件处理。该类定义了Connect()与DisConnect()方法实现与客户端的连接与断开连接。当登陆到指定的服务器时,调用ClientReceive类实现消息收发,同时该类还定义了SendMessaga()方法来其他用户发送带有表情的消息或悄悄话。

1 /* 2* To change this license header, choose License Headers in Project Properties. 3* To change this template file, choose Tools | Templates 4* and open the template in the editor. 5*/ 6 package com.silianbo.client; 7 8 /** 9* 10* @author silianbo 11* 客户端主界面 12*/ 13 import com.silianbo.CaptureScreen; 14 import static com.silianbo.CaptureScreen.captureScreen; 15 import com.silianbo.client.ConnectConf; 16 import com.silianbo.client.Help; 17 import com.silianbo.client.UserConf; 18 19 import com.sun.security.ntlm.Client; 20 import java.awt.BorderLayout; 21 import java.awt.Component; 22 import java.awt.Container; 23 import java.awt.Dimension; 24 import java.awt.GridBagConstraints; 25 import java.awt.GridBagLayout; 26 import java.awt.Insets; 27 import java.awt.Toolkit; 28 import java.awt.event.ActionEvent; 29 import java.awt.event.ActionListener; 30 import java.awt.event.WindowAdapter; 31 import java.awt.event.WindowEvent; 32 import java.io.ObjectInputStream; 33 import java.io.ObjectOutputStream; 34 import java.net.Socket; 35 import java.util.logging.Level; 36 import java.util.logging.Logger; 37 import javax.swing.JButton; 38 import javax.swing.JCheckBox; 39 import javax.swing.JComboBox; 40 import javax.swing.JFrame; 41 import javax.swing.JLabel; 42 import javax.swing.JMenu; 43 import javax.swing.JMenuBar; 44 import javax.swing.JMenuItem; 45 import javax.swing.JOptionPane; 46 import javax.swing.JPanel; 47 import javax.swing.JScrollPane; 48 import javax.swing.JTextArea; 49 import javax.swing.JTextField; 50 import javax.swing.JToolBar; 51 import javax.swing.UIManager; 52 import javax.swing.UnsupportedLookAndFeelException; 53 54 /* 55* 聊天客户端的主框架类 56*/ 57 public final class ChatClient extends JFrame implements ActionListener { 58 59/** 60* 版本控制,默认版本控制1L 61*/ 62private static final long serialVersionUID = 1L; 63 64String ip = "127.0.0.1"; //连接到服务端的ip地址 65int port = 8888; //连接到服务端的端口号 66String userName = "silianbo"; //用户名 67int type = 0; //,用户连接标记,其中0表示未连接,1表示已连接 68 69JComboBox combobox; //选择发送消息的接受者 70JTextArea messageShow; //客户端的信息显示 71JScrollPane messageScrollPane; //信息显示的滚动条 72 73JLabel express, sendToLabel, messageLabel; 74 75JTextField clientMessage; //客户端消息的发送 76JCheckBox checkbox; //悄悄话 77JComboBox actionlist; //表情选择 78JButton clientMessageButton; //发送消息 79JTextField showStatus; //显示用户连接状态 80 81Socket socket; 82ObjectOutputStream output; //网络套接字输出流 83ObjectInputStream input; //网络套接字输入流 84 85ClientReceive recvThread; 86 87//建立菜单栏 88JMenuBar jMenuBar = new JMenuBar(); 89//建立菜单组 90JMenu operateMenu = new JMenu("操作"); 91//建立菜单项 92JMenuItem loginItem = new JMenuItem("用户登录"); 93JMenuItem logoffItem = new JMenuItem("用户注销"); 94JMenuItem exitItem = new JMenuItem("退出"); 95 96JMenu conMenu = new JMenu("设置"); 97JMenuItem userItem = new JMenuItem("用户设置"); 98JMenuItem connectItem = new JMenuItem("连接设置"); 99 100JMenu helpMenu = new JMenu("帮助"); 101JMenuItem helpItem = new JMenuItem("帮助"); 102 103//建立工具栏 104JToolBar toolBar = new JToolBar(); 105 106//建立工具栏中的按钮组件 107JButton loginButton; //用户登录 108JButton logoffButton; //用户注销 109JButton userButton; //用户信息的设置 110JButton connectButton; //连接设置 111JButton exitButton; //退出按钮 112JButton captureScreenButton; //截屏按钮 113 114//框架的大小 115Dimension faceSize = new Dimension(550, 550); 116 117JPanel downPanel; 118GridBagLayout girdBag; 119GridBagConstraints girdBagCon; 120 121public ChatClient() { 122init(); //初始化程序 123 124//添加框架的关闭事件处理 125this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 126this.pack(); 127//设置框架的大小 128this.setSize(faceSize); 129 130//设置运行时窗口的位置 131Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 132this.setLocation((int) (screenSize.width - faceSize.getWidth()) / 2, 133(int) (screenSize.height - faceSize.getHeight()) / 2); 134this.setResizable(false); 135this.setTitle("聊天室客户端"); //设置标题 136 137setVisible(true); 138 139//为操作菜单栏设置热键'V' 140operateMenu.setMnemonic('O'); 141 142} 143 144/** 145* 程序初始化函数 146*/ 147public void init() { 148 149Container contentPane = getContentPane(); 150contentPane.setLayout(new BorderLayout()); 151 152//添加菜单栏,对应55行相关介绍 153jMenuBar.add(operateMenu); //操作(1.2.3) 154operateMenu.add(loginItem); //1.用户登录 155operateMenu.add(logoffItem); //2.用户注销 156operateMenu.add(exitItem); //2.退出 157 158jMenuBar.add(conMenu); //设置(a.b) 159conMenu.add(userItem); //a.用户设置 160conMenu.add(connectItem); //b.连接设置 161 162jMenuBar.add(helpMenu); //帮助(I) 163helpMenu.add(helpItem); //I.帮助 164 165setJMenuBar(jMenuBar); 166 167//初始化按钮 168loginButton = new JButton("登录"); 169logoffButton = new JButton("注销"); 170userButton = new JButton("用户设置"); 171connectButton = new JButton("连接设置"); 172exitButton = new JButton("退出"); 173captureScreenButton = new JButton("全屏截屏"); 174JButtonscreenShotButton = new JButton("区域截图"); 175 176//当鼠标放上显示信息 177loginButton.setToolTipText("连接到指定的服务器"); 178logoffButton.setToolTipText("与服务器断开连接"); 179userButton.setToolTipText("设置用户信息"); 180connectButton.setToolTipText("设置所要连接到的服务器信息"); 181captureScreenButton.setToolTipText("现在只能全屏截下全屏"); 182//将按钮添加到工具栏 183toolBar.add(userButton); 184Component add = toolBar.add(connectButton); 185toolBar.addSeparator(); //添加分隔栏 186toolBar.add(loginButton); 187toolBar.add(logoffButton); 188toolBar.addSeparator(); //添加分隔栏 189toolBar.add(exitButton); 190toolBar.add(captureScreenButton); 191toolBar.add(screenShotButton); 192 193contentPane.add(toolBar, BorderLayout.NORTH); 194 195checkbox = new JCheckBox("悄悄话"); 196checkbox.setSelected(false); 197 198actionlist = new JComboBox(); 199actionlist.addItem("@/微笑@"); 200actionlist.addItem("@/高兴@"); 201actionlist.addItem("@/轻轻@"); 202actionlist.addItem("@/生气@"); 203actionlist.addItem("@/小心@"); 204actionlist.addItem("@/静静@"); 205actionlist.setSelectedIndex(0); 206 207//初始时 208loginButton.setEnabled(true); 209logoffButton.setEnabled(false); 210 211//为菜单栏添加事件监听 212loginItem.addActionListener(this); 213logoffItem.addActionListener(this); 214exitItem.addActionListener(this); 215userItem.addActionListener(this); 216connectItem.addActionListener(this); 217helpItem.addActionListener(this); 218 219//添加按钮的事件侦听 220loginButton.addActionListener(this); 221logoffButton.addActionListener(this); 222userButton.addActionListener(this); 223connectButton.addActionListener(this); 224exitButton.addActionListener(this); 225 226/* 227*全屏截屏事件监听处理 228*/ 229captureScreenButton.addActionListener((ActionEvent e) -> { 230try { 231CaptureScreen.RandomName filename = new CaptureScreen.RandomName(); 232captureScreen("C:\\Users\\silianbo\\Desktop\\计算机网络课程设计\\image", filename + ".png"); 233} catch (Exception ex) { 234Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); 235} 236}); 237/** 238* 区域截屏监听 239*/ 240screenShotButton.addActionListener(this); 241 242combobox = new JComboBox(); 243combobox.insertItemAt("所有人", 0); 244combobox.setSelectedIndex(0); 245 246messageShow = new JTextArea(); 247messageShow.setEditable(false); 248//添加滚动条 249messageScrollPane = new JScrollPane(messageShow, 250JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 251JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 252messageScrollPane.setPreferredSize(new Dimension(400, 400)); 253messageScrollPane.revalidate(); 254 255clientMessage = new JTextField(23); 256clientMessage.setEnabled(false); 257clientMessageButton = new JButton(); 258clientMessageButton.setText("发送"); 259 260//添加系统消息的事件侦听 261clientMessage.addActionListener(this); 262clientMessageButton.addActionListener(this); 263 264sendToLabel = new JLabel("发送至:"); 265express = new JLabel("表情:"); 266messageLabel = new JLabel("发送消息:"); 267downPanel = new JPanel(); 268girdBag = new GridBagLayout(); 269downPanel.setLayout(girdBag); 270 271girdBagCon = new GridBagConstraints(); 272girdBagCon.gridx = 0; 273girdBagCon.gridy = 0; 274girdBagCon.gridwidth = 5; 275girdBagCon.gridheight = 2; 276girdBagCon.ipadx = 5; 277girdBagCon.ipady = 5; 278JLabel none = new JLabel(""); 279girdBag.setConstraints(none, girdBagCon); 280downPanel.add(none); 281 282girdBagCon = new GridBagConstraints(); 283girdBagCon.gridx = 0; 284girdBagCon.gridy = 2; 285girdBagCon.insets = new Insets(1, 0, 0, 0); 286//girdBagCon.ipadx = 5; 287//girdBagCon.ipady = 5; 288girdBag.setConstraints(sendToLabel, girdBagCon); 289downPanel.add(sendToLabel); 290 291girdBagCon = new GridBagConstraints(); 292girdBagCon.gridx = 1; 293girdBagCon.gridy = 2; 294girdBagCon.anchor = GridBagConstraints.LINE_START; 295girdBag.setConstraints(combobox, girdBagCon); 296downPanel.add(combobox); 297 298girdBagCon = new GridBagConstraints(); 299girdBagCon.gridx = 2; 300girdBagCon.gridy = 2; 301girdBagCon.anchor = GridBagConstraints.LINE_END; 302girdBag.setConstraints(express, girdBagCon); 303downPanel.add(express); 304 305girdBagCon = new GridBagConstraints(); 306girdBagCon.gridx = 3; 307girdBagCon.gridy = 2; 308girdBagCon.anchor = GridBagConstraints.LINE_START; 309//girdBagCon.insets = new Insets(1,0,0,0); 310//girdBagCon.ipadx = 5; 311//girdBagCon.ipady = 5; 312girdBag.setConstraints(actionlist, girdBagCon); 313downPanel.add(actionlist); 314 315girdBagCon = new GridBagConstraints(); 316girdBagCon.gridx = 4; 317girdBagCon.gridy = 2; 318girdBagCon.insets = new Insets(1, 0, 0, 0); 319 //girdBagCon.ipadx = 5; 320 //girdBagCon.ipady = 5; 321girdBag.setConstraints(checkbox, girdBagCon); 322downPanel.add(checkbox); 323 324girdBagCon = new GridBagConstraints(); 325girdBagCon.gridx = 0; 326girdBagCon.gridy = 3; 327girdBag.setConstraints(messageLabel, girdBagCon); 328downPanel.add(messageLabel); 329 330girdBagCon = new GridBagConstraints(); 331girdBagCon.gridx = 1; 332girdBagCon.gridy = 3; 333girdBagCon.gridwidth = 3; 334girdBagCon.gridheight = 1; 335girdBag.setConstraints(clientMessage, girdBagCon); 336downPanel.add(clientMessage); 337 338girdBagCon = new GridBagConstraints(); 339girdBagCon.gridx = 4; 340girdBagCon.gridy = 3; 341girdBag.setConstraints(clientMessageButton, girdBagCon); 342downPanel.add(clientMessageButton); 343 344showStatus = new JTextField(35); 345showStatus.setEditable(false); 346girdBagCon = new GridBagConstraints(); 347girdBagCon.gridx = 0; 348girdBagCon.gridy = 5; 349girdBagCon.gridwidth = 5; 350girdBag.setConstraints(showStatus, girdBagCon); 351downPanel.add(showStatus); 352 353contentPane.add(messageScrollPane, BorderLayout.CENTER); 354contentPane.add(downPanel, BorderLayout.SOUTH); 355 356//关闭程序时的操作 357this.addWindowListener( 358new WindowAdapter() { 359@Override 360public void windowClosing(WindowEvent e) { 361if (type == 1) { 362DisConnect(); 363} 364System.exit(0); 365} 366} 367); 368} 369 370/** 371* 事件处理 372*/ 373@Override 374public void actionPerformed(ActionEvent e) { 375Object obj = e.getSource(); 376 377if (obj == userItem || obj == userButton) { //用户信息设置 378//调出用户信息设置对话框 379UserConf userConf = new UserConf(this, userName); 380userConf.setVisible(true); 381userName = userConf.userInputName; 382} else if (obj == connectItem || obj == connectButton) { //连接服务端设置 383//调出连接设置对话框 384ConnectConf conConf = new ConnectConf(this, ip, port); 385conConf.setVisible(true); 386ip = conConf.userInputIp; 387port = conConf.userInputPort; 388} else if (obj == loginItem || obj == loginButton) { //登录 389Connect(); 390} else if (obj == logoffItem || obj == logoffButton) { //注销 391DisConnect(); 392showStatus.setText(""); 393} else if (obj == clientMessage || obj == clientMessageButton) { //发送消息 394SendMessage(); 395clientMessage.setText(""); 396} else if (obj == exitButton || obj == exitItem) { //退出 397int j = JOptionPane.showConfirmDialog( 398this, "真的要退出吗?", "退出", 399JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE); 400 401if (j == JOptionPane.YES_OPTION) { 402if (type == 1) { 403DisConnect(); 404} 405System.exit(0); 406} 407} else if (obj == helpItem) { //菜单栏中的帮助 408//调出帮助对话框 409Help helpDialog = new Help(this); 410helpDialog.setVisible(true); 411} 412} 413 /** 414* 连接服务器 415*/ 416public void Connect() { 417try { 418socket = new Socket(ip, port); 419} catch (Exception e) { 420JOptionPane.showConfirmDialog( 421this, "不能连接到指定的服务器。\n请确认连接设置是否正确。", "提示", 422JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); 423return; 424} 425 426try { 427output = new ObjectOutputStream(socket.getOutputStream()); 428output.flush(); 429 430input = new ObjectInputStream(socket.getInputStream()); 431 432output.writeObject(userName); 433output.flush(); 434 435recvThread = new ClientReceive(socket, output, input, combobox, messageShow, showStatus); 436recvThread.start(); 437 438loginButton.setEnabled(false); 439loginItem.setEnabled(false); 440userButton.setEnabled(false); 441userItem.setEnabled(false); 442connectButton.setEnabled(false); 443connectItem.setEnabled(false); 444logoffButton.setEnabled(true); 445logoffItem.setEnabled(true); 446clientMessage.setEnabled(true); 447messageShow.append("连接服务器 " + ip + ":" + port + " 成功...\n"); 448type = 1; //标志位设为已连接 449} catch (Exception e) { 450System.out.println(e); 451} 452} 453 454/** 455*服务器注销 456*/ 457public void DisConnect() { 458loginButton.setEnabled(true); 459loginItem.setEnabled(true); 460userButton.setEnabled(true); 461userItem.setEnabled(true); 462connectButton.setEnabled(true); 463connectItem.setEnabled(true); 464logoffButton.setEnabled(false); 465logoffItem.setEnabled(false); 466clientMessage.setEnabled(false); 467 468if (socket.isClosed()) { 469return; 470} 471 472try { 473output.writeObject("用户下线"); 474output.flush(); 475 476input.close(); 477output.close(); 478socket.close(); 479messageShow.append("已经与服务器断开连接...\n"); 480type = 0; //标志位设为未连接 481} catch (Exception e) { 482// 483} 484} 485 486public void SendMessage() { 487String toSomebody = combobox.getSelectedItem().toString(); 488String status = ""; 489if (checkbox.isSelected()) { 490status = "悄悄话"; 491} 492 493String action = actionlist.getSelectedItem().toString(); 494String message = clientMessage.getText(); 495 496if (socket.isClosed()) { 497return; 498} 499 500try { 501output.writeObject("聊天信息"); 502output.flush(); 503output.writeObject(toSomebody); 504output.flush(); 505output.writeObject(status); 506output.flush(); 507output.writeObject(action); 508output.flush(); 509output.writeObject(message); 510output.flush(); 511} catch (Exception e) { 512// 513} 514} 515 516public static void main(String[] args) throws UnsupportedLookAndFeelException { 517try { 518UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 519} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { 520} 521ChatClient chatClient = new ChatClient(); 522} 523 }


ConnectConf.java
该类继承自Jdialog,是用户对所有要连接的服务器IP及监听端口进行修改配置的类
基于java网络聊天室--客户端
文章图片
基于java网络聊天室--客户端
文章图片
1 /* 2* To change this license header, choose License Headers in Project Properties. 3* To change this template file, choose Tools | Templates 4* and open the template in the editor. 5*/ 6 package com.silianbo.client; 7 8 import java.awt.BorderLayout; 9 import java.awt.Container; 10 import java.awt.Dimension; 11 import java.awt.GridLayout; 12 import java.awt.Label; 13 import java.awt.Toolkit; 14 import java.awt.event.ActionEvent; 15 import java.awt.event.WindowAdapter; 16 import java.awt.event.WindowEvent; 17 import java.net.InetAddress; 18 import java.net.UnknownHostException; 19 import javax.swing.JButton; 20 import javax.swing.JDialog; 21 import javax.swing.JFrame; 22 import javax.swing.JLabel; 23 import javax.swing.JPanel; 24 import javax.swing.JTextField; 25 26 /** 27* 28* @author silianbo 29* 生成连接信息输入的对话框 让用户输入连接服务器的IP和端口 30*/ 31 public class ConnectConf extends JDialog { 32 33/** 34* 35*/ 36private static final long serialVersionUID = 1L; 37JPanel panelUserConf = new JPanel(); 38JButton save = new JButton(); 39JButton cancel = new JButton(); 40JLabel DLGINFO = new JLabel( 41"默认连接设置为127.0.0.1:8888"); 42 43JPanel panelSave = new JPanel(); 44JLabel message = new JLabel(); 45 46String userInputIp; 47int userInputPort; 48 49JTextField inputIp; 50JTextField inputPort; 51 52public ConnectConf(JFrame frame, String ip, int port) { 53super(frame, true); 54this.userInputIp = ip; 55this.userInputPort = port; 56try { 57jbInit(); 58} catch (Exception e) { 59} 60//设置运行位置,使对话框居中 61Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 62this.setLocation((int) (screenSize.width - 400) / 2 + 50, 63(int) (screenSize.height - 600) / 2 + 150); 64this.setResizable(false); 65} 66 67private void jbInit() throws Exception { 68this.setSize(new Dimension(300, 130)); 69this.setTitle("连接设置"); 70message.setText(" 请输入服务器的IP地址:"); 71inputIp = new JTextField(10); 72inputIp.setText(userInputIp); 73inputPort = new JTextField(4); 74inputPort.setText("" + userInputPort); 75save.setText("保存"); 76cancel.setText("取消"); 77 78panelUserConf.setLayout(new GridLayout(2, 2, 1, 1)); 79panelUserConf.add(message); 80panelUserConf.add(inputIp); 81panelUserConf.add(new JLabel(" 请输入服务器的端口号:")); 82panelUserConf.add(inputPort); 83 84panelSave.add(new Label("")); 85panelSave.add(save); 86panelSave.add(cancel); 87panelSave.add(new Label("")); 88 89Container contentPane = getContentPane(); 90contentPane.setLayout(new BorderLayout()); 91contentPane.add(panelUserConf, BorderLayout.NORTH); 92contentPane.add(DLGINFO, BorderLayout.CENTER); 93contentPane.add(panelSave, BorderLayout.SOUTH); 94 95//保存按钮的事件处理 96save.addActionListener((ActionEvent a) -> { 97int savePort; 98//判断端口号是否合法 99try { 100userInputIp = "" + InetAddress.getByName(inputIp.getText()); 101userInputIp = userInputIp.substring(1); 102} catch (UnknownHostException e) { 103DLGINFO.setText( 104"错误的IP地址!"); 105 106return; 107} 108//userInputIp = inputIP; 109 110//判断端口号是否合法 111try { 112savePort = Integer.parseInt(inputPort.getText()); 113 114if (savePort < 1 || savePort > 65535) { 115DLGINFO.setText("侦听端口必须是0-65535之间的整数!"); 116inputPort.setText(""); 117return; 118} 119userInputPort = savePort; 120dispose(); 121} catch (NumberFormatException e) { 122DLGINFO.setText("错误的端口号,端口号请填写整数!"); 123inputPort.setText(""); 124} 125}); 126 127//关闭对话框时的操作 128this.addWindowListener( 129new WindowAdapter() { 130@Override 131public void windowClosing(WindowEvent e) { 132DLGINFO.setText("默认连接设置为127.0.0.1:8888"); 133} 134} 135); 136 137//取消按钮的事件处理 138cancel.addActionListener((ActionEvent e) -> { 139DLGINFO.setText("默认连接设置为127.0.0.1:8888"); 140dispose(); 141}); 142} 143 }

View Code UserConf.java
该类继承自Jdialog,是用户对链接到服务器时所显示的用户名进行修改配置的类。
基于java网络聊天室--客户端
文章图片
基于java网络聊天室--客户端
文章图片
1 /* 2* To change this license header, choose License Headers in Project Properties. 3* To change this template file, choose Tools | Templates 4* and open the template in the editor. 5*/ 6 package com.silianbo.client; 7 8 import java.awt.*; 9 import javax.swing.*; 10 import java.awt.event.*; 11 /** 12* 13* @author silianbo 14* 生成用户信息输入对话框的类 15* 让用户输入自己的用户名 16*/ 17 public class UserConf extends JDialog { 18/** 19* 20*/ 21private static final long serialVersionUID = 1L; 22JPanel panelUserConf = new JPanel(); 23JButton save = new JButton(); 24JButton cancel = new JButton(); 25JLabel DLGINFO=new JLabel( 26"默认用户名为:silianbo"); 27 28JPanel panelSave = new JPanel(); 29JLabel message = new JLabel(); 30String userInputName; 31 32JTextField userName ; 33 34public UserConf(JFrame frame,String str) { 35super(frame, true); 36this.userInputName = str; 37try { 38jbInit(); 39} 40catch (Exception e) { 41e.printStackTrace(); 42} 43//设置运行位置,使对话框居中 44Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 45this.setLocation( (int) (screenSize.width - 400) / 2 + 50, 46(int) (screenSize.height - 600) / 2 + 150); 47this.setResizable(false); 48} 49 50private void jbInit() throws Exception { 51this.setSize(new Dimension(300, 120)); 52this.setTitle("用户设置"); 53message.setText("请输入用户名:"); 54userName = new JTextField(10); 55userName.setText(userInputName); 56save.setText("保存"); 57cancel.setText("取消"); 58 59panelUserConf.setLayout(new FlowLayout()); 60panelUserConf.add(message); 61panelUserConf.add(userName); 62 63panelSave.add(new Label("")); 64panelSave.add(save); 65panelSave.add(cancel); 66panelSave.add(new Label("")); 67 68Container contentPane = getContentPane(); 69contentPane.setLayout(new BorderLayout()); 70contentPane.add(panelUserConf, BorderLayout.NORTH); 71contentPane.add(DLGINFO, BorderLayout.CENTER); 72contentPane.add(panelSave, BorderLayout.SOUTH); 73 74//保存按钮的事件处理 75save.addActionListener( 76new ActionListener() { 77public void actionPerformed (ActionEvent a) { 78if(userName.getText().equals("")){ 79DLGINFO.setText( 80"用户名不能为空!"); 81userName.setText(userInputName); 82return; 83} 84else if(userName.getText().length() > 15){ 85DLGINFO.setText("用户名长度不能大于15个字符!"); 86userName.setText(userInputName); 87return; 88} 89userInputName = userName.getText(); 90dispose(); 91} 92} 93); 94 95//关闭对话框时的操作 96this.addWindowListener( 97new WindowAdapter(){ 98@Override 99public void windowClosing(WindowEvent e){ 100DLGINFO.setText("默认用户名为:silianbo"); 101} 102} 103); 104 105//取消按钮的事件处理 106cancel.addActionListener((ActionEvent e) -> { 107DLGINFO.setText("默认用户名为:silianbo"); 108dispose(); 109}); 110} 111 }

View Code Help.java
客户端程序的帮助类
基于java网络聊天室--客户端
文章图片
基于java网络聊天室--客户端
文章图片
1 /* 2* To change this license header, choose License Headers in Project Properties. 3* To change this template file, choose Tools | Templates 4* and open the template in the editor. 5*/ 6 package com.silianbo.client; 7 8 /** 9* 10* @author silianbo 11*/ 12 import java.awt.*; 13 import javax.swing.*; 14 import java.awt.event.*; 15 16 /** 17* 生成设置对话框的类 18*/ 19 public class Help extends JDialog { 20 21/** 22* 23*/ 24private static final long serialVersionUID = 1L; 25JPanel titlePanel = new JPanel(); 26JPanel contentPanel = new JPanel(); 27JPanel closePanel = new JPanel(); 28 29JButton close = new JButton(); 30JLabel title = new JLabel("聊天室客户端帮助"); 31JTextArea help = new JTextArea(); 32 33Color bg = new Color(255,255,255); 34 35public Help(JFrame frame) { 36super(frame, true); 37try { 38jbInit(); 39} 40catch (Exception e) { 41e.printStackTrace(); 42} 43//设置运行位置,使对话框居中 44Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 45this.setLocation( (int) (screenSize.width - 400) / 2 + 25, 46(int) (screenSize.height - 320) / 2); 47this.setResizable(false); 48} 49 50private void jbInit() throws Exception { 51this.setSize(new Dimension(350, 270)); 52this.setTitle("帮助"); 53 54titlePanel.setBackground(bg); ; 55contentPanel.setBackground(bg); 56closePanel.setBackground(bg); 57 58help.setText("1、设置所要连接服务端的IP地址和端口"+ 59"(默认设置为\n127.0.0.1:8888)。\n"+ 60"2、输入你的用户名(默认设置为:silianbo)。\n"+ 61"3、点击“登录”便可以连接到指定的服务器;\n"+ 62"点击“注销”可以和服务器端开连接。\n"+ 63"4、选择需要接受消息的用户,在消息栏中写入消息,\n"+ 64"同时选择表情,之后便可发送消息。\n"); 65help.setEditable(false); 66 67titlePanel.add(new Label("")); 68titlePanel.add(title); 69titlePanel.add(new Label("")); 70 71contentPanel.add(help); 72 73closePanel.add(new Label("")); 74closePanel.add(close); 75closePanel.add(new Label("")); 76 77Container contentPane = getContentPane(); 78contentPane.setLayout(new BorderLayout()); 79contentPane.add(titlePanel, BorderLayout.NORTH); 80contentPane.add(contentPanel, BorderLayout.CENTER); 81contentPane.add(closePanel, BorderLayout.SOUTH); 82 83close.setText("关闭"); 84//事件处理 85close.addActionListener((ActionEvent e) -> { 86dispose(); 87}); 88} 89 }

View Code ClientReceive.java
该类是实现服务器端与客户端消息收发的类
基于java网络聊天室--客户端
文章图片
基于java网络聊天室--客户端
文章图片
1 /* 2* To change this license header, choose License Headers in Project Properties. 3* To change this template file, choose Tools | Templates 4* and open the template in the editor. 5*/ 6 package com.silianbo.client; 7 8 import java.io.IOException; 9 import java.io.ObjectInputStream; 10 import java.io.ObjectOutputStream; 11 import java.net.Socket; 12 import javax.swing.JComboBox; 13 import javax.swing.JTextArea; 14 import javax.swing.JTextField; 15 16 /** 17* 18* @author silianbo 19* 聊天客户端消息收发类 20*/ 21 public class ClientReceive extends Thread { 22private final JComboBox combobox; 23private final JTextArea textarea; 24 25Socket socket; 26ObjectOutputStream output; 27ObjectInputStreaminput; 28JTextField showStatus; 29 30public ClientReceive(Socket socket,ObjectOutputStream output, 31ObjectInputStreaminput,JComboBox combobox,JTextArea textarea,JTextField showStatus){ 32 33this.socket = socket; 34this.output = output; 35this.input = input; 36this.combobox = combobox; 37this.textarea = textarea; 38this.showStatus = showStatus; 39} 40 41@Override 42public void run(){ 43while(!socket.isClosed()){ 44try{ 45String type = (String)input.readObject(); 46 47if(type.equalsIgnoreCase("系统信息")){ 48String sysmsg = (String)input.readObject(); 49textarea.append("系统信息: "+sysmsg); 50} 51else if(type.equalsIgnoreCase("服务关闭")){ 52output.close(); 53input.close(); 54socket.close(); 55 56textarea.append("服务器已关闭!\n"); 57 58break; 59} 60else if(type.equalsIgnoreCase("聊天信息")){ 61String message = (String)input.readObject(); 62textarea.append(message); 63} 64else if(type.equalsIgnoreCase("用户列表")){ 65String userlist = (String)input.readObject(); 66String usernames[] = userlist.split("\n"); 67combobox.removeAllItems(); 68 69int i =0; 70combobox.addItem("所有人"); 71while(i < usernames.length){ 72combobox.addItem(usernames[i]); 73i ++; 74} 75combobox.setSelectedIndex(0); 76showStatus.setText("在线用户 " + usernames.length + " 人"); 77} 78} 79catch (IOException | ClassNotFoundException e ){ 80System.out.println(e); 81} 82} 83} 84 }

View Code
【基于java网络聊天室--客户端】转载于:https://www.cnblogs.com/silianbo/p/4638538.html

    推荐阅读