java网络编程聊天室
时间: 2023-12-13 16:04:41 浏览: 104
Java网络编程聊天室是一种基于Java语言实现的网络聊天室,可以让多个用户在同一时间内进行在线聊天。下面是一个简单的Java网络编程聊天室的实现过程:
1. 创建服务器端
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getInetAddress().getHostAddress());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = br.readLine()) != null) {
System.out.println("客户端说:" + msg);
}
}
}
}
```
2. 创建客户端
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8888);
System.out.println("已连接服务器...");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
String msg;
while ((msg = br.readLine()) != null) {
pw.println(msg);
}
}
}
```
3. 运行程序
首先运行服务器端程序,然后运行多个客户端程序,客户端程序可以在控制台输入聊天内容,服务器端程序会将聊天内容输出到控制台。
阅读全文