2.编写多线程的UDP网络程序: 编写数据接收类ReceiveThread,该类实现了Runnable接口,重写run()方法实现不断接受客户端发送数据的功能;编写数据发送类SendThread,该类同样实现了SendThread接口,重写run()方法实现通过键盘录入数据,将数据向接收端发送的功能。
时间: 2023-12-10 10:38:58 浏览: 85
下面是一个示例代码,实现了多线程的UDP网络程序:
```java
import java.io.*;
import java.net.*;
public class ReceiveThread implements Runnable {
DatagramSocket socket;
public ReceiveThread(DatagramSocket socket) {
this.socket = socket;
}
public void run() {
try {
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (true) {
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + received);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class SendThread implements Runnable {
DatagramSocket socket;
InetAddress address;
int port;
public SendThread(DatagramSocket socket, InetAddress address, int port) {
this.socket = socket;
this.address = address;
this.port = port;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String message = reader.readLine();
byte[] buf = message.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class MultiThreadedUDP {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(12345);
InetAddress address = InetAddress.getByName("localhost");
Thread receiveThread = new Thread(new ReceiveThread(socket));
Thread sendThread = new Thread(new SendThread(socket, address, 12346));
receiveThread.start();
sendThread.start();
receiveThread.join();
sendThread.join();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个示例程序中,我们创建了两个线程:一个用于接收数据,一个用于发送数据。接收数据的线程实现了Runnable接口,重写了run()方法,通过不断调用socket.receive()方法来接收数据,并将接收到的数据打印出来。发送数据的线程同样实现了Runnable接口,重写了run()方法,通过从键盘读入数据并将其发送给指定的地址和端口。
在主函数中,我们创建了一个DatagramSocket对象,绑定到本地的12345端口,并将要发送数据的地址设置为localhost,端口设置为12346。然后创建两个线程,并分别启动它们。最后调用join()方法等待两个线程执行完成。
阅读全文