怎么用java实现一个简易的聊天室

69次阅读
没有评论

共计 3211 个字符,预计需要花费 9 分钟才能阅读完成。

要实现一个简易的聊天室,可以使用 Java 的 Socket 编程实现。下面是一个简单的实现示例:

服务器端代码:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {private ServerSocket serverSocket;
    private List<ClientHandler> clients = new ArrayList<>();

    public static void main(String[] args) {ChatServer server = new ChatServer();
        server.start(8888);
    }

    public void start(int port) {try {serverSocket = new ServerSocket(port);
            System.out.println(" 服务器已启动,监听端口:" + port);

            while (true) {Socket clientSocket = serverSocket.accept();
                System.out.println(" 客户端已连接:" + clientSocket.getRemoteSocketAddress());

                // 创建一个新的客户端处理器
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                clients.add(clientHandler);
                clientHandler.start();}
        } catch (IOException e) {e.printStackTrace();
        }
    }

    public synchronized void broadcast(String message, ClientHandler excludeClient) {for (ClientHandler client : clients) {if (client != excludeClient) {client.sendMessage(message);
            }
        }
    }

    public synchronized void removeClient(ClientHandler client) {clients.remove(client);
    }

    private class ClientHandler extends Thread {private Socket clientSocket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public ClientHandler(Socket clientSocket) {this.clientSocket = clientSocket;
        }

        @Override
        public void run() {try {inputStream = clientSocket.getInputStream();
                outputStream = clientSocket.getOutputStream();

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {String message = new String(buffer, 0, bytesRead);
                    System.out.println(" 收到消息:" + message);

                    // 广播消息给其他客户端
                    broadcast(message, this);
                }
            } catch (IOException e) {e.printStackTrace();
            } finally {try {clientSocket.close();
                    removeClient(this);
                } catch (IOException e) {e.printStackTrace();
                }
            }
        }

        public void sendMessage(String message) {try {outputStream.write(message.getBytes());
                outputStream.flush();} catch (IOException e) {e.printStackTrace();
            }
        }
    }
}

客户端代码:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient {private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public static void main(String[] args) {ChatClient client = new ChatClient();
        client.connect("localhost", 8888);
    }

    public void connect(String serverAddress, int serverPort) {try {socket = new Socket(serverAddress, serverPort);
            System.out.println(" 已连接到服务器:" + serverAddress + ":" + serverPort);

            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();

            // 接收和发送消息的线程
            Thread receiveThread = new Thread(this::receiveMessages);
            Thread sendThread = new Thread(this::sendMessages);

            receiveThread.start();
            sendThread.start();} catch (IOException e) {e.printStackTrace();
        }
    }

    public void receiveMessages() {try {byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {String message = new String(buffer, 0, bytesRead);
                System.out.println(message);
            }
        } catch (IOException e) {e.printStackTrace();
        }
    }

    public void sendMessages() {Scanner scanner = new Scanner(System.in);
        try {while (true) {String message = scanner.nextLine();
                outputStream.write(message.getBytes());
                outputStream.flush();}
        } catch (IOException e) {e.printStackTrace();
        }
    }
}

在命令行中,先运行服务器端的 ChatServer 类,再运行客户端的 ChatClient 类。客户端可以输入消息,然后服务器端会将消息广播给其他客户端。注意要将客户端的 connect 方法中的 serverAddress 改为服务器的 IP 地址。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计3211字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)