中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

怎么用java實現一個簡易的聊天室

小億
139
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
隆安县| 唐山市| 赤壁市| 霍山县| 昌宁县| 保德县| 新干县| 综艺| 忻州市| 大丰市| 湟源县| 广德县| 徐州市| 海城市| 万州区| 齐河县| 崇信县| 鹤壁市| 枝江市| 漾濞| 长沙市| 丘北县| 枣强县| 九江县| 新乡市| 雅江县| 定安县| 林西县| 乌什县| 特克斯县| 临洮县| 九江市| 镇平县| 莱芜市| 介休市| 新平| 汕头市| 东山县| 嘉义县| 三亚市| 嘉荫县|