温馨提示×

java怎么实现一对一聊天

小亿
83
2024-12-07 08:18:35
栏目: 编程语言

在Java中实现一对一聊天,你可以使用Socket编程和ObjectOutputStream/ObjectInputStream。以下是一个简单的示例,展示了如何创建一个简单的一对一聊天应用程序。

  1. 首先,创建一个名为ChatServer.java的服务器端类:
import java.io.*;
import java.net.*;

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

            Socket socket = serverSocket.accept();
            System.out.println("Client connected");

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

            String message;
            while ((message = (String) ois.readObject()) != null) {
                System.out.println("Received: " + message);
                oos.writeObject("Server received: " + message);
            }

            socket.close();
            serverSocket.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
  1. 然后,创建一个名为ChatClient.java的客户端类:
import java.io.*;
import java.net.*;

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

        try (Socket socket = new Socket(serverAddress, port);
             ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {

            BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
            String userMessage;

            while ((userMessage = userInput.readLine()) != null && !userMessage.equalsIgnoreCase("exit")) {
                oos.writeObject(userMessage);
                System.out.println("Server response: " + ois.readObject());
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

现在,你可以运行ChatServer.java来启动服务器,然后运行ChatClient.java来启动客户端。客户端将能够与服务器进行一对一聊天。要退出聊天,请在客户端输入"exit"。

请注意,这个示例仅用于演示目的,实际应用中可能需要考虑更多因素,例如错误处理、多线程以支持多个客户端连接等。

0