多线程实现UDP协议发送和接收
package 多线程实现UDP协议发送和接收;
import java.io.IOException;
import java.net.DatagramSocket;
经过对原有聊天程序的优化升级,并引入多线程机制后,现在能够在一个窗口内实现数据发送与接收功能。
创建一个新的SendThread实例st,并将其配置为dsSend。
创建一个新的ReceiveThread实例rt,并将其配置为dsReceive。
Thread t1 = new Thread(st);
Thread t2 = new Thread(rt);
t1.start();
t2.start();
}
}
package 多线程实现UDP协议发送和接收;
Import the IOException class from the java.io package. Import the DatagramPacket class from the java.net package. Import the DatagramSocket class from the java.net package.
定义一个名为ReceiveThread的可运行类。
该类实现了接收数据的相关功能。
私有字段ds用于接收数据。
public ReceiveThread(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
while (true) {
// 创建一个包裹
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
// 接收数据
ds.receive(dp);
// 解析过程
通过获取地址对象的主机地址属性来确定IP地址:ip = dp.getAddress().getHostAddress();
接着构造一个名为s的新字符串对象:调用新字符串构造函数,并传递dp.getData()作为初始字符序列,默认填充至该序列长度。
输出信息:"从IP地址:" + ip + "处获取的数据为:" + s。
}
捕获异常部分:
catch(IOException e) {
打印异常详情:e.printStackTrace();
}
}
package 多线程实现UDP协议发送和接收;
导入伯德伯格流对象库
导入伯德伯格异常对象库
导入伯德伯格缓冲流接口
导入 Datagram 包acket 对象
导入 Datagram 子套接字接口
倒入 InetAddress 类
public class SendThread implements Runnable {
private DatagramSocket ds;
public SendThread(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
// 封装键盘录入数据
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
}
// 数据打包与传输
byte[] bys = line.getBytes();
// 使用 DatagramPacket 实例化构建数据包
DatagramPacket dp = new DatagramPacket(bys,
bys.length,
InetAddress.getByName("niuchengfei"),
12306);
// 发送数据
ds.send(dp);
}
// 释放资源
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
