逐行分析解释下面代码:import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket server = new ServerSocket(8888); // 监听指定端口号 System.out.println("等待客户端连接..."); Socket socket = server.accept(); // 等待客户端连接 System.out.println("客户端已连接,IP地址为:" + socket.getInetAddress().getHostAddress()); // 为客户端创建读取器和写入器 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // 启动一个线程来接收客户端发送的消息 Thread receiveThread = new Thread(() -> { try { while (true) { String message = reader.readLine(); if (message == null) { break; } System.out.println("客户端说:" + message); } } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); writer.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }); receiveThread.start(); // 主线程用于发送消息 BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String message = consoleReader.readLine(); writer.println(message); writer.flush(); } } catch (IOException e) { e.printStackTrace(); } } }
时间: 2024-01-07 20:03:36 浏览: 80
这段代码实现了一个简单的Socket服务器,接收客户端发送的消息并将其输出到控制台,同时也可以通过控制台向客户端发送消息。
1. 导入必要的包:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
```
2. 在主函数中,创建一个ServerSocket对象并指定端口号为8888,然后等待客户端连接:
```java
ServerSocket server = new ServerSocket(8888); // 监听指定端口号
System.out.println("等待客户端连接...");
Socket socket = server.accept(); // 等待客户端连接
System.out.println("客户端已连接,IP地址为:" + socket.getInetAddress().getHostAddress());
```
3. 创建一个BufferedReader对象和一个PrintWriter对象,用于读取和写入数据:
```java
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
```
4. 创建一个线程用于接收客户端发送的消息,该线程通过while循环不断地读取客户端发送的消息,并将其输出到控制台:
```java
Thread receiveThread = new Thread(() -> {
try {
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println("客户端说:" + message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
receiveThread.start();
```
5. 在主线程中,通过BufferedReader对象从控制台读入消息,并通过PrintWriter对象将其发送给客户端:
```java
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = consoleReader.readLine();
writer.println(message);
writer.flush();
}
```
6. 若有异常,则打印异常信息:
```java
} catch (IOException e) {
e.printStackTrace();
}
```
阅读全文