无法设置datagramPacket对象中缓冲区的偏移量 [英] Unable to set the offset for buffer in the datagramPacket object

查看:331
本文介绍了无法设置datagramPacket对象中缓冲区的偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java库中, http:/ /download.java.net/jdk7/archive/b123/docs/api/java/net/DatagramPacket.html

我想构造我的数据报包使用此构造函数的对象;

I want to construct my datagram packet object using this constructor;

DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)

这是我的代码:

      ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
      outputStream.write( by); // by is a buffer that contains filename
      outputStream.write(buffer); // buffer contains the actual data for the packet
      byte combined[] = outputStream.toByteArray( );
      System.out.println("combined length is "+combined.length);
      sndPkt = new DatagramPacket(combined,by.length, combined.length, ip, portNum);


      sendsocket.send(sndPkt);
      Thread.sleep(1);

by是包含文件名的缓冲区。 缓冲区包含文件数据。我想将它们组合在一起并发送一个小包。但是,当我使用上述构造函数创建DatagramPacket对象时。我收到此错误消息:

"by" is a buffer that contains filename. "buffer" contains the file data. I want to combine them together and send in one packet. However, when I create the DatagramPacket object with the above mentioned constructor. I got this error message:

   java.lang.IllegalArgumentException: illegal length or offset

当我将其更改为零时,没有错误报告,但是我需要将偏移值设置为与文件名长度相同,以便能够在服务器端获取它。谁能告诉我问题出在哪里?我可以通过将文件名作为第一个数据包发送到服务器来发送文件名,但是现在我想将文件名嵌入到我发送的每个数据包中。这是执行此操作的标准方法吗?

When I change it to zero, no error is reported, but I need to set the offset value same as my filename length so that I am able to get it at the server side. Can anyone tell me where the problem is? I am able to send the filename over to the server by sending it as the first packet, but now I want to embed the filename in every packet I send. Is this the standard way of doing this?

推荐答案

偏移量+长度必须小于或等于缓冲区的长度,否则它将被溢出。发送/接收的数据将从缓冲区中的偏移量开始,并以 length 长的长度运行。

offset + length must be less than or equal to the length of the buffer, or it will be overrun. The data sent/received will start at the offset in the buffer and run for length long.

如果在代码中使用 offset = 0 ,则确实会在每个数据包中发送文件名。但是,由于您不知道接收到的数据包中文件名的长度,因此在解析数据包时会遇到麻烦。例如,您可以在文件名和其余数据之间添加分隔符,并相应地解析数据包。

If you use offset=0 in your code you will indeed send the file name in each packet. However, you will have trouble parsing the packet since you do not know the length of the file name in the received packet. You can for example add a separator between the file name and the rest of the data and parse the packet accordingly.

这篇关于无法设置datagramPacket对象中缓冲区的偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆