编写数据接收类ReceiveThread,该类实现了Runnable接口,重写run()方法实现不断接受客户端发送数据的功能;编写数据发送类SendThread,该类同样实现了SendThread接口,重写run()方法实现通过键盘录入数据,将数据向接收端发送的功能。
时间: 2023-12-10 18:37:37 浏览: 57
下面是ReceiveThread和SendThread的代码示例:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ReceiveThread implements Runnable {
private Socket socket;
public ReceiveThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message;
while ((message = reader.readLine()) != null) {
System.out.println("Received message: " + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
```
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class SendThread implements Runnable {
private Socket socket;
public SendThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
Scanner scanner = new Scanner(System.in);
String message;
while ((message = scanner.nextLine()) != null) {
writer.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码实现了客户端发送和接收数据的功能,需要在客户端的主函数中创建并启动这两个线程。
阅读全文