编写多线程的UDP网络程序: 编写数据接收类ReceiveThread,该类实现了Runnable接口,重写run()方法实现不断接受客户端发送数据的功能;编写数据发送类SendThread,该类同样实现了SendThread接口,重写run()方法实现通过键盘录入数据,将数据向接收端发送的功能。
时间: 2023-12-10 15:38:37 浏览: 72
Java多线程-创建多线程的基本方式二:实现Runnable接口
下面是一个简单的多线程UDP网络程序实现:
```
import java.io.IOException;
import java.net.*;
public class ReceiveThread implements Runnable {
DatagramSocket ds;
public ReceiveThread(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println("接收到数据:" + str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class SendThread implements Runnable {
DatagramSocket ds;
InetAddress address;
int port;
public SendThread(DatagramSocket ds, InetAddress address, int port) {
this.ds = ds;
this.address = address;
this.port = port;
}
@Override
public void run() {
try {
while (true) {
byte[] buf = new byte[1024];
System.in.read(buf);
DatagramPacket dp = new DatagramPacket(buf, buf.length, address, port);
ds.send(dp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class UDPMultiThread {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(8888);
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 9999;
Thread t1 = new Thread(new ReceiveThread(ds));
Thread t2 = new Thread(new SendThread(ds, address, port));
t1.start();
t2.start();
}
}
```
在这个例子中,我们创建了两个线程,一个用于接收数据,一个用于发送数据。ReceiveThread类实现了Runnable接口,并覆盖了run()方法,该方法通过DatagramSocket对象接收数据包并将其打印到控制台。SendThread类同样实现了Runnable接口,并覆盖了run()方法,该方法从键盘读取数据并将其发送到指定的地址和端口。UDPMultiThread类是程序的入口,创建了DatagramSocket对象、接收方地址和端口,并启动了两个线程来接收和发送数据。
阅读全文