java聊天室项目
时间: 2023-08-22 20:08:55 浏览: 77
java-chatroom.zip_java 聊天室_聊天室
Java聊天室项目是一个非常有趣的项目,可以帮助您学习Java编程语言和网络编程。以下是一个简单的Java聊天室项目示例,可以帮助您入门:
1. 创建一个服务器类,该类将监听客户端连接并发送/接收消息。以下是一个示例代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Server started");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
out.println("Server: " + inputLine);
}
socket.close();
System.out.println("Client disconnected");
}
}
}
```
2. 创建一个客户端类,该类将连接到服务器并发送/接收消息。以下是一个示例代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8000);
System.out.println("Connected to server");
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("Server: " + in.readLine());
}
socket.close();
System.out.println("Disconnected from server");
}
}
```
3. 运行服务器和客户端,并开始发送消息以进行测试。
这只是一个简单的Java聊天室项目示例,您可以根据自己的需求进行修改和扩展。例如,您可以添加多个客户端,并将消息广播到所有客户端。
阅读全文