在Java中使用DatagramPacket

时间:2012-12-10 14:02:00

标签: java datagram

要通过DatagramPacket发送字符串,我们使用:

 String msg = "example";
 byte[]data = msg.getBytes();
 DatagramPacket pktOut = new DatagramPacket(data, 0, data.length, dest, port)

如何通过DatagramPacket发送数组?

 int num[] = {50,20,45,82,25,63};
 //I need to send this over two packets, but I don't know how to deal
//with arrays when sending them

提前谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用ByteBuffer类将Integer数组转换为字节缓冲区。

int num[] = { 50 , 20 , 45 , 82 , 25 , 63 };
ByteBuffer bb = ByteBuffer.allocate( num.length * 4 );
for ( int i : num ) {
    bb.putInt( i );
}
byte[] data = bb.array();