2012-12-10 17 views
1

使用的DatagramPacket要發送通過我們使用DatagramPacket類的字符串:在Java中

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

這是什麼意思? 問題是:我不知道如何開始轉換這個數組到一個表單,它可以通過一個包發送..代碼示例plz? –

回答

2

您可以在整數數組轉換成使用ByteBuffer類的字節的緩衝區。

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(); 
+0

爲什麼你用num.length * 4? –

+0

由於整數有4個字節,緩衝區應該爲num [](6 * 4 = 24個字節)中的所有整數分配足夠的空間。 – stacker