Java

java如何实现聊天程序

小亿
82
2024-12-07 09:24:40
栏目: 编程语言

实现一个简单的聊天程序可以使用Java的Socket编程。以下是一个基本的示例,展示了如何创建一个简单的聊天服务器和客户端。

1. 创建聊天服务器

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    public static void main(String[] args) throws IOException {
        int port = 12345;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server started on port " + port);

        List<PrintWriter> clients = new ArrayList<>();

        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("New client connected: " + socket.getInetAddress());

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            clients.add(out);

            Thread clientThread = new Thread(() -> {
                try {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        System.out.println("Received from " + socket.getInetAddress() + ": " + inputLine);
                        for (PrintWriter clientOut : clients) {
                            if (!socket.equals(clientOut.getSocket())) {
                                clientOut.println(socket.getInetAddress() + ": " + inputLine);
                            }
                        }
                    }
                } catch (IOException e) {
                    System.out.println("Client disconnected: " + socket.getInetAddress());
                } finally {
                    clients.remove(out);
                    socket.close();
                }
            });

            clientThread.start();
        }
    }
}

2. 创建聊天客户端

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatClient {
    public static void main(String[] args) throws IOException {
        String serverAddress = "localhost";
        int port = 12345;

        Socket socket = new Socket(serverAddress, port);
        System.out.println("Connected to server: " + serverAddress + ":" + port);

        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        Thread inputThread = new Thread(() -> {
            try {
                String userInput;
                while ((userInput = stdIn.readLine()) != null && !userInput.equalsIgnoreCase("exit")) {
                    out.println(userInput);
                    System.out.println("Server response: " + in.readLine());
                }
            } catch (IOException e) {
                System.out.println("Connection closed");
            } finally {
                socket.close();
            }
        });

        inputThread.start();
    }
}

运行步骤

  1. 启动服务器

    • 编译并运行 ChatServer 类。
    • 服务器将在端口 12345 上启动。
  2. 启动客户端

    • 编译并运行 ChatClient 类。
    • 客户端将连接到服务器。
  3. 发送和接收消息

    • 在客户端的命令行界面中输入消息并按回车键。
    • 消息将被发送到服务器,并由服务器广播给所有连接的客户端。

注意事项

0
看了该问题的人还看了