Unable to set the offset for buffer in the datagra

2019-08-20 18:41发布

In the java library, 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)

Here is my code:

      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" 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?

1条回答
别忘想泡老子
2楼-- · 2019-08-20 18:51

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.

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.

查看更多
登录 后发表回答