java实现多人聊天系统

2023-05-16 0 1,725

本文实例大家分享了java实现多人聊天系统具体代码,供大家参考,具体内容如下

开发环境

Windows 7 操作系统
MyEclipse

聊天室程序结构设计

1.系统分为客户端、服务器端和连接服务器客户端三个模块。
2.客户端负责发送消息。
3.服务器端负责接收客户端发来的信息并执行相应操作处理,最后通过群发功能,使客户端将群聊的消息的显示出来。
4.连接服务器端负责连接服务器,从而进入客户端。

总体模块图

java实现多人聊天系统

客户端代码

Client.java

package servlet;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.OutputStreamWriter;

public class Client {
              Socket socket;
              BufferedWriter bw;
              BufferedReader br ;
        
public Client(String ip, int port){
         try {
              socket =new Socket(ip,port);
              bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
              br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
              }catch (UnknownHostException e){
              e.printStackTrace();
              }catch(IOException e){
              e.printStackTrace();
                }
    }
public void sendMessage(String message) {
          try{ 
              bw.write(message);
              bw.newLine();
              bw.flush();
       }catch(IOException e){
             e.printStackTrace();
    
     }
   }

public String reciveMessage() {
       String message=null;
       try { 
           message = br.readLine();
      }catch(IOException e) {
          e.printStackTrace();
      }
    return message;
}

public void close(){
     try{
     socket.close();
    }catch(IOException e){
    e.printStackTrace();
    }
}}

ClientFrame.java

package servlet;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Date;


import javax.swing.*;
import javax.swing.border.EmptyBorder;


public class ClientFrame extends JFrame {
    private JPanel contentPane;
    private JLabel lblUserName;
    private JTextField tfMessage;
    private JButton btnSend;
    private JTextArea textArea;
    private String userName;
    private Client client;

public ClientFrame(String ip,String userName){
    this.userName = userName;
    init();//添加窗体初始化内容
    addListener();
    client=new Client(ip,8080);
    ReadMessageThread t=new ReadMessageThread();
    t.start();
}
private class ReadMessageThread extends Thread{
     public void run() {
      while(true) {
          String str=client.reciveMessage();
          textArea.append(str+\"\\n\");//添加文本内容
      }
  }
  
}
private void init(){
   setTitle(\"客户端\");
   setResizable(false);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setBounds(100,100,450,300);

   contentPane = new JPanel();
   contentPane.setBorder(new EmptyBorder(5,5,5,5));
   contentPane.setLayout(null);
   setContentPane(contentPane);

   JScrollPane scrollPane = new JScrollPane();
   scrollPane.setBounds(5,5,434,229);
   contentPane.add(scrollPane);

  textArea =new JTextArea();
  scrollPane.setViewportView(textArea);
  textArea .setEditable(false);

  JPanel panel =new JPanel();
  panel.setBounds(5,235,434,32);
  contentPane.add(panel);
  panel.setLayout(null);

  lblUserName = new JLabel(userName);
  lblUserName.setHorizontalAlignment(SwingConstants.TRAILING);
  lblUserName.setBounds(2,4,55,22);
  panel.add(lblUserName);

  tfMessage =new JTextField();
  tfMessage.setBounds(62,5,274,22);
  tfMessage.setColumns(10);
  panel.add(tfMessage);

  btnSend =new JButton(\"发送\");
  btnSend.setBounds(336,4,93,23);
  panel.add(btnSend);

  tfMessage.validate();
}
private void addListener(){
 btnSend.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent e){
        Date date=new Date();
        SimpleDateFormat sf=new SimpleDateFormat(\"yyyy年MM月dd日 HH:mm:ss\");
        client.sendMessage(userName+\"\"+sf.format(date)+\":\\n\"+tfMessage.getText());
        tfMessage.setText(\"\");//清空

          }
      });
   this.addWindowListener(new WindowAdapter(){//开启窗口监听
    public void windowClosing(WindowEvent atg0) {
        int op = JOptionPane.showConfirmDialog(ClientFrame.this,\"确定要退出聊天室吗?\",\"确定\",JOptionPane.YES_NO_OPTION);
        if(op == JOptionPane.YES_OPTION) {
            client.sendMessage(\"%EXIT%:\" + userName);
            try {
                Thread.sleep(200);
                
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
            client.close();
            System.exit(0);
        }
         }
      });
  }
}

LinkServerFrame.java

package servlet;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

@SuppressWarnings(\"serial\")
public class LinkServerFrame extends JFrame {

    private JPanel contentPane;//下方面板
    private JLabel lblIP;
    private JLabel lblUserName;
    private JTextField tfIP;
    private JTextField tfUserName;
    private JButton btnLink;


   public LinkServerFrame(){
    setTitle(\"连接服务器\");
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 390, 150);

   contentPane = new JPanel();
   contentPane.setBorder(new EmptyBorder(5,5,5,5));
   contentPane.setLayout(null);
   setContentPane(contentPane);

   lblIP =new JLabel(\"服务器IP地址:\");
   lblIP.setFont(new Font(\"微软雅黑\",Font.PLAIN,14));
   lblIP.setBounds(20,15,100,15);
   contentPane.add(lblIP);

   tfIP =new JTextField(\"127.0.0.1\");
   tfIP.setBounds(121,13,242,21);
   contentPane.add(tfIP);
   tfIP.setColumns(10);

   lblUserName = new JLabel(\"用户名:\");
  lblUserName.setFont(new Font(\"微软雅黑\",Font.PLAIN,14));
  lblUserName.setBounds(60,40,60,15);
   contentPane.add(lblUserName);

   tfUserName =new JTextField();
  tfUserName.setBounds(121,42,242,21);
  contentPane.add(tfUserName);
  tfUserName.setColumns(10);

  btnLink =new JButton(\"连接服务器\");
  btnLink.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
      do_btnlink_actionPerformed(e);
  }
   });
  btnLink.setFont(new Font(\"微软雅黑\",Font.PLAIN,14));
   btnLink.setBounds(140,80,120,23);
   contentPane.add(btnLink);//显示连接服务器窗口
 }
public static void main(String[] args){
     LinkServerFrame linkServerFrame = new LinkServerFrame();
     linkServerFrame.setVisible(true);
}
  protected void do_btnlink_actionPerformed(ActionEvent e) {
      if(!tfIP.getText().equals(\"\")&&!tfUserName.getText().equals(\"\")) {//文本框的内容不能为空
          dispose();//销毁当前窗口
         ClientFrame clientFrame=new ClientFrame(tfIP.getText().trim(), tfUserName.getText().trim());
          clientFrame.setVisible(true);//显示客户窗体
      }
      else {
          JOptionPane.showMessageDialog(null,\"文本框里的内容不能为空!\",\"警告\",JOptionPane.WARNING_MESSAGE);
      }
       }
}

服务器端代码

Server.java

package servlet;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Server {
   private HashSet<Socket> allSocket;
   private ServerSocket server;


 public Server() {
     try {
        server = new ServerSocket(8080);
  }catch(IOException e) {

      e.printStackTrace();
  }
     allSocket=new HashSet<Socket>();
 } 
 public void startServer() throws IOException{
     while(true) {
         Socket socket =server.accept();
         System.out.println(\"用户已经进入聊天室\");
         allSocket.add(socket);
         ServerThread t= new ServerThread(socket);
         t.start();
        
     }
 }
 private class ServerThread extends Thread{
       Socket socket;
     public ServerThread(Socket socket) {
       this.socket=socket;
     }
    public void run() {
         BufferedReader br=null;
         try {
            br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while(true) {
                String str=br.readLine();
                if(str.contains(\"%EXIT%\")) {
                  String tmp=str.split(\":\")[1]+\"用户退出聊天室\";
                 sendMessageToALLClient(tmp);
                 allSocket.remove(socket);
                 socket.close();
                 return;    
                }
                sendMessageToALLClient(str);
            }
         }catch(IOException e) {
                e.printStackTrace();
            
         }
     }}
    private void sendMessageToALLClient(String str) throws IOException {
    for(Socket s: allSocket) {
        try{
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        bw.write(str);
        bw.newLine();
        bw.flush();
    }catch(IOException e) {
        e.printStackTrace();
            
         }
    }
 }
 public static void main(String[] args) {
     Server s = new Server();
     try {
         s.startServer();
     }catch(IOException e){
         e.printStackTrace();
     }
     }
 }

操作步骤

1.先运行服务器端代码(server.java)建立连接,然后运行客户端(LinkServerFrame.java)输入用户名

java实现多人聊天系统

2.登入成功之后会显示用户已经进入聊天室

java实现多人聊天系统

3.进入多人聊天室

java实现多人聊天系统

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

资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 java实现多人聊天系统 https://www.20zxx.cn/704797/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务