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

全栈工程师开发手册 (作者:栾鹏)
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) {
		}
	}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

腾讯AI架构师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值