UDP传输优化后的代码:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public classSendDemo {
public static void main(String[] args) throws IOException {
// 创建发送端的Socket对象
DatagramSocketds = newDatagramSocket();
// 创建数据并打包
byte[] bys = "helloworld".getBytes();
DatagramPacketdp = newDatagramPacket(bys, bys.length,
InetAddress.getByName("219.216.80.19"),12345);
// 发送数据
ds.send(dp);
// 释放资源
ds.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/*
* 多次启动接收端:
* java.net.BindException:Address already in use: Cannot bind
* 端口被占用。
*/
public classReceiveDemo {
public static void main(String[] args) throws IOException {
// 创建接收端的Socket对象
DatagramSocketds = newDatagramSocket(12345);
// 创建一个包裹
byte[] bys = new byte[1024];
DatagramPacketdp = newDatagramPacket(bys, bys.length);
// 接收数据
ds.receive(dp);
// 解析数据
Stringip = dp.getAddress().getHostAddress();
Strings = newString(dp.getData(), 0, dp.getLength());
System.out.println("from "+ ip + " data is : " + s);
// 释放资源
ds.close();
}
}
运行结果:
from 219.216.80.19 data is : helloworld