java发送接收UDP数据包:字符串,byte[]字节数组,文件等

时间:2025-04-17 07:08:06

全栈工程师开发手册 (作者:栾鹏)
java教程全解

java发送接收UDP数据包,数据内容为byte[],包括一切可以转换为byte[]的内容。

测试代码

 public static void main(String args[]) 
    {
    	sendUDPfile("127.0.0.1",1234,"D:\\");  //发送文件
    	//启动新线程发送数据,
    	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)();    // 文件长度
              message = new byte[len];      // 建立缓冲区
              FileInputStream in = new FileInputStream(f);
              int bytes_read = 0, n;
              do {   // 从文件中读取
                  n = (message, bytes_read, len-bytes_read);
                  bytes_read += n;
              } while((bytes_read < len)&& (n != -1));
              sendUDP(host, port, message);
		} catch (Exception e) {
			();
		}
}

使用UDP发送byte[]数据流

public static void sendUDP(String host,int port,byte[] message) 
{
    try { 
        // 根据主机名称得到IP地址
        InetAddress address = (host);
        // 用数据和地址创建数据报文包
        DatagramPacket packet = new DatagramPacket(message, , address, port);
 
        // 创建数据报文套接字并通过它传送
        DatagramSocket dsocket = new DatagramSocket();
        (packet);
        ();
    }
    catch (Exception e) {
        (e);
    }
}

从指定端口接收UDP数据

	public static void receiveUDP(int port) {
		try {
			byte[] buffer = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buffer, );
			DatagramSocket socket = new DatagramSocket(port);
			while (true) {
				(packet);
				String s = new String(buffer, 0, 0, ());
				("接收到数据:"+s);
				packet = new DatagramPacket(buffer, );
			}
		} catch (Exception e) {
		}
	}