实现一个简单的聊天程序可以使用Java的Socket编程。以下是一个基本的示例,展示了如何创建一个简单的聊天服务器和客户端。
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();
}
}
}
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();
}
}
启动服务器:
ChatServer
类。12345
上启动。启动客户端:
ChatClient
类。发送和接收消息: