![](https://i-blog.csdnimg.cn/blog_migrate/11ab61846568f7310c1fec6b75306fcd.jpeg)
全栈工程师开发手册 (作者:栾鹏)
java教程全解
java发送接收UDP数据包,数据内容为byte[],包括一切可以转换为byte[]的内容。
测试代码
public static void main(String args[])
{
sendUDPfile("127.0.0.1",1234,"D:\\test1.zip"); //发送文件
//启动新线程发送数据,
new Thread(new Runnable() {
@Override
public void run() {
sendUDP("127.0.0.1",9999,"hello".getBytes()); //发送字节数据
}
}).start();
//在主线程中接收数据
receiveUDP(9999); //接收数据
}
使用UDP发送文件
public static void sendUDPfile(String host,int port,String filepath)
{
try {
File f=new File(filepath);
byte[] message; // 要传送的数据
int len = (int)f.length(); // 文件长度
message = new byte[len]; // 建立缓冲区
FileInputStream in = new FileInputStream(f);
int bytes_read = 0, n;
do { // 从文件中读取
n = in.read(message, bytes_read, len-bytes_read);
bytes_read += n;
} while((bytes_read < len)&& (n != -1));
sendUDP(host, port, message);
} catch (Exception e) {
e.printStackTrace();
}
}
使用UDP发送byte[]数据流
public static void sendUDP(String host,int port,byte[] message)
{
try {
// 根据主机名称得到IP地址
InetAddress address = InetAddress.getByName(host);
// 用数据和地址创建数据报文包
DatagramPacket packet = new DatagramPacket(message, message.length, address, port);
// 创建数据报文套接字并通过它传送
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
}
catch (Exception e) {
System.err.println(e);
}
}
从指定端口接收UDP数据
public static void receiveUDP(int port) {
try {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(port);
while (true) {
socket.receive(packet);
String s = new String(buffer, 0, 0, packet.getLength());
System.out.println("接收到数据:"+s);
packet = new DatagramPacket(buffer, buffer.length);
}
} catch (Exception e) {
}
}