2015-11-03 49 views
-2

發送陣列(未排列的列表)我有陣列這樣在客戶端通過UDP

INT ARR [] =新INT [] {1,6,3,1,2,9};

我怎麼可以通過UDP發送到服務器?以及我如何在SERVER端讀取它?

回答

1

將數組轉換爲字節數組,然後發送字節數組。接收器將字節數組轉換回int [];您可以使用類DataOutputStream創建字節數組。

ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    DataOutputStream dos = new DataOutputStream(bos); 
    int len = 0; 
    in protokollVersion = 1; 
    // Write a version, in case you want to change your format later, such that 
    // the receiver has a chance to detect which format version is used. 
    dos.writeInt(protokollVersion); 
    if (arr != null) { 
     len = arr.length; 
    } 
    dos.writeInt(arr.length); 
    for (int i = 0; i < len; i++) { 
     dos.writeInt(arr[i]); 
    } 
    dos.close(); 
    byte[] bytes = bos.getBytes(); 

在接收器側,讀取使用DataInputStream(byte[] bytes)DataInputStream.readInt()字節數組。

+0

你能告訴我如何轉換它嗎?因爲我沒有從谷歌搜索找到很多幫助。 –

+0

已更新的答案。 – AlexWien