温馨提示×

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

小亿
154
2023-10-31 19:38:36
栏目: 编程语言

要实现一个简易的聊天室,可以使用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地址。

0