一对多聊天室

2023-12-13 15:43:24

多人聊天包

由于要先创建服务面板,接收客户端连接的信息,此代码使用顺序为先启动服务端,在启动客户端,服务端不用关,不然会报错。多运行几次客户端,实现单人聊天

创建服务面板

package yiduiduo;
 
 
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
 
public class Ltmb extends JFrame {
    private JTextArea ta_info;
    private ServerSocket server; // 声明ServerSocket对象
    private Socket socket; // 声明Socket对象socket
    private Hashtable<String, Socket> map = new Hashtable<String, Socket>();// 用于存储连接到服务器的用户和客户端套接字对象
    
    public void createSocket() {
        try {
            server = new ServerSocket(1978);
            while (true) {
                ta_info.append("等待新客户连接......\n");
                socket = server.accept();// 创建套接字对象
                ta_info.append("客户端连接成功。" + socket + "\n");
                new ServerThread(socket).start();// 创建并启动线程对象
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    class ServerThread extends Thread {
        Socket socket;
        
        public ServerThread(Socket socket) {
            this.socket = socket;
        }
        
        public void run() {
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));// 创建输入流对象
                while (true) {
                    String info = in.readLine();// 读取信息
                    String key = "";
                    if (info.startsWith("用户:")) {// 添加登录用户到客户端列表
                        key = info.substring(3, info.length());// 获得用户名并作为键使用
                        map.put(key, socket);// 添加键值对
                        Set<String> set = map.keySet();// 获得集合中所有键的Set视图
                        Iterator<String> keyIt = set.iterator();// 获得所有键的迭代器
                        while (keyIt.hasNext()) {
                            String receiveKey = keyIt.next();// 获得表示接收信息的键
                            Socket s = map.get(receiveKey);// 获得与该键对应的套接字对象
                            PrintWriter out = new PrintWriter(s
                                    .getOutputStream(), true);// 创建输出流对象
                            Iterator<String> keyIt1 = set.iterator();// 获得所有键的迭代器
                            while (keyIt1.hasNext()) {
                                String receiveKey1 = keyIt1.next();// 获得键,用于向客户端添加用户列表
                                out.println(receiveKey1);// 发送信息
                                out.flush();// 刷新输出缓冲区
                            }
                        }
                        
                    } else {// 转发接收的消息
                        key = info.substring(info.indexOf(":发送给:") + 5, info
                                .indexOf(":的信息是:"));// 获得接收方的key值,即接收方的用户名
                        String sendUser = info.substring(0, info
                                .indexOf(":发送给:"));// 获得发送方的key值,即发送方的用户名
                        Set<String> set = map.keySet();// 获得集合中所有键的Set视图
                        Iterator<String> keyIt = set.iterator();// 获得所有键的迭代器
                        while (keyIt.hasNext()) {
                            String receiveKey = keyIt.next();// 获得表示接收信息的键
                            if (key.equals(receiveKey)
                                    && !sendUser.equals(receiveKey)) {// 如果是发送方,但不是用户本身
                                Socket s = map.get(receiveKey);// 获得与该键对应的套接字对象
                                PrintWriter out = new PrintWriter(s
                                        .getOutputStream(), true);// 创建输出流对象
                                
                                out.println("MSG:"+info);// 发送信息
                                out.flush();// 刷新输出缓冲区
                            }
                        }
                    }
                }
            } catch (IOException e) {
                ta_info.append(socket + "已经退出。\n");
            }
        }
    }
    
  
    public static void main(String args[]) {
        Ltmb frame = new Ltmb();
        frame.setVisible(true);
        frame.createSocket();
    }
    
 
    public Ltmb() {
        super();
        setTitle("多个用户聊天");
        setBounds(100, 100, 385, 266);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        
        ta_info = new JTextArea();
        scrollPane.setViewportView(ta_info);
    }
}

创建客户面板

package yiduiduo;
 
 
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
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.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class Kehuduan extends JFrame {
    private JTextArea ta_info;
    private JTextField tf_send;
    PrintWriter out;// 声明输出流对象
    
    /**
     * Launch the application
     * 
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                   Kehuduan frame = new Kehuduan();
                    frame.setVisible(true);
                    frame.createClientSocket();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    public void createClientSocket() {
        try {
            Socket socket = new Socket("127.0.0.1", 1978);// 连接本地1978端口
            out = new PrintWriter(socket.getOutputStream(), true);// 创建输出流对象
            new ClientThread(socket).start();// 创建并启动线程对象
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    class ClientThread extends Thread {
        Socket socket;
        
        public ClientThread(Socket socket) {
            this.socket = socket;
        }
        
        public void run() {
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));// 创建输入流对象
                while (true) {
                    String info = in.readLine();// 读取信息
                    ta_info.append(info + "\n");// 在文本域中显示信息
                    if (info.equals("88")) {
                        break;// 结束线程
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void send() {
        String info = tf_send.getText();// 获得输入的信息
        if (info.equals("")) {
            return;// 如果没输入信息则返回,即不发送
        }
        if (info.equals("88")) {
            System.exit(0);// 如果没输入信息是88,则退出
        }
        out.println(info);// 发送信息
        out.flush();// 刷新输出缓冲区
        tf_send.setText(null);// 清空文本框
    }
    
   
    public Kehuduan() {  //创建面板
        super();
        setTitle("客户互相聊天");
        setBounds(100, 100, 385, 266);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        final JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.SOUTH);
        
        final JLabel label = new JLabel();
        label.setText("输入聊天内容:");
        panel.add(label);
        
        tf_send = new JTextField();
        tf_send.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                send();
            }
        });
        tf_send.setPreferredSize(new Dimension(180, 25));
        panel.add(tf_send);
        
        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                send();
            }
        });
        button.setText("发  送");
        panel.add(button);
        
        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        
        ta_info = new JTextArea();
        scrollPane.setViewportView(ta_info);
        
    }
    
}

结果如下

文章来源:https://blog.csdn.net/s1133333/article/details/134847252
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。