java 聊天源码
时间: 2023-07-05 15:06:06 浏览: 50
以下是一个简单的 Java 聊天室的源码,基于 Java Socket 实现:
服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
static final int PORT = 5000;
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(PORT);
System.out.println("Server started.");
while (true) {
Socket socket = server.accept();
System.out.println("New client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Welcome to the chat room.");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Message from client: " + inputLine);
out.println("You said: " + inputLine);
}
in.close();
out.close();
socket.close();
}
}
}
```
客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
static final String HOST = "localhost";
static final int PORT = 5000;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(HOST, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
}
in.close();
out.close();
stdIn.close();
socket.close();
}
}
```
运行 Server 类,然后运行多个 Client 类进行模拟多人聊天。