import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class Client { public static void main(String[] args) { new Client().go();// 创建一个新的 client 对象,并调用 go() 方法 } public void go() { try { Socket sock = new Socket("127.0.0.1", 5000); InputStreamReader streamReader = new InputStreamReader(sock.getInputStream()); BufferedReader reader = new BufferedReader(streamReader); PrintWriter writer = new PrintWriter(sock.getOutputStream()); System.out.println("Connected to server."); System.out.println("请输入你想对服务端说的话:"); Thread readerThread = new Thread(new IncomingReader(reader)); readerThread.start(); Scanner userInput = new Scanner(System.in); while (true) { String message = userInput.nextLine(); writer.println(message); writer.flush(); } } catch (Exception ex) { ex.printStackTrace(); } } public class IncomingReader implements Runnable { BufferedReader reader; public IncomingReader(BufferedReader reader) { this.reader = reader; } public void run() { String message; try { while ((message = reader.readLine()) != null) { System.out.println(message); } } catch (Exception ex) { ex.printStackTrace(); } } } }请在原有代码的基础上添加对应的注释
时间: 2024-02-10 20:07:28 浏览: 184
下面是针对给出代码的注释说明:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
new Client().go(); // 创建一个新的 client 对象,并调用 go() 方法
}
public void go() {
try {
Socket sock = new Socket("127.0.0.1", 5000); // 创建 Socket 连接到指定 IP 地址和端口号
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream()); // 创建输入流读取服务器发送的消息
BufferedReader reader = new BufferedReader(streamReader);
PrintWriter writer = new PrintWriter(sock.getOutputStream()); // 创建输出流向服务器发送消息
System.out.println("Connected to server."); // 连接成功,输出提示信息
System.out.println("请输入你想对服务端说的话:");
Thread readerThread = new Thread(new IncomingReader(reader)); // 创建一个线程用于读取服务器发送的消息
readerThread.start(); // 启动线程
Scanner userInput = new Scanner(System.in); // 创建 Scanner 对象,用于读取用户输入的消息
while (true) {
String message = userInput.nextLine(); // 读取用户输入的消息
writer.println(message); // 向服务器发送消息
writer.flush(); // 立即刷新输出流
}
} catch (Exception ex) {
ex.printStackTrace(); // 捕获并打印异常
}
}
public class IncomingReader implements Runnable { // 该类实现 Runnable 接口,用于在新线程中读取服务器发送的消息
BufferedReader reader;
public IncomingReader(BufferedReader reader) {
this.reader = reader;
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) { // 循环读取服务器发送的消息
System.out.println(message); // 输出服务器发送的消息
}
} catch (Exception ex) {
ex.printStackTrace(); // 捕获并打印异常
}
}
}
}
```
阅读全文