2017-10-07 99 views
1

我有運行與發送和接收TCP連接的工作代碼。 這裏是我的CreateCommThreadTaskWriteToServerCloseSocketTask類:Android的 - 轉換TCP客戶端UDP客戶

private class CreateCommThreadTask extends AsyncTask 
     <Void, Integer, Void> { 
    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      //---create a socket--- 
      serverAddress = 
        InetAddress.getByName("192.168.4.1"); 
      socket = new Socket(serverAddress, 8080); 
      commsThread = new CommsThread(socket); 
      commsThread.start(); 
     } catch (UnknownHostException e) { 
      Log.d("Sockets", e.getLocalizedMessage()); 
     } catch (IOException e) { 
      Log.d("Sockets", e.getLocalizedMessage()); 
     } 
     return null; 
    } 
} 

private class WriteToServerTask extends AsyncTask 
     <byte[], Void, Void> { 
    protected Void doInBackground(byte[]...data) { 
     commsThread.write(data[0]); 
     return null; 
    } 
} 

private class CloseSocketTask extends AsyncTask 
     <Void, Void, Void> { 
    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      socket.close(); 
     } catch (IOException e) { 
      Log.d("Sockets", e.getLocalizedMessage()); 
     } 
     return null; 
    } 
} 

,並用這個類我讀的輸入數據:

public class CommsThread extends Thread { 
private final Socket socket; 
private final InputStream inputStream; 
private final OutputStream outputStream; 

public CommsThread(Socket sock) { 
    socket = sock; 
    InputStream tmpIn = null; 
    OutputStream tmpOut = null; 
    try { 
     //---creates the inputstream and outputstream objects 
     // for reading and writing through the sockets--- 
     tmpIn = socket.getInputStream(); 
     tmpOut = socket.getOutputStream(); 
    } catch (IOException e) { 
     Log.d("SocketChat", e.getLocalizedMessage()); 
    } 
    inputStream = tmpIn; 
    outputStream = tmpOut; 
} 

public void run() { 
    //---buffer store for the stream--- 
    byte[] buffer = new byte[1024]; 

    //---bytes returned from read()--- 
    int bytes; 

    //---keep listening to the InputStream until an 
    // exception occurs--- 
    while (true) { 
     try { 
      //---read from the inputStream--- 
      bytes = inputStream.read(buffer); 

      //---update the main activity UI--- 
      SocketsActivity.UIupdater.obtainMessage(
       0,bytes, -1, buffer).sendToTarget(); 
     } catch (IOException e) { 
      break; 
     } 
    } 
} 

//---call this from the main activity to 
// send data to the remote device--- 
public void write(byte[] bytes) { 
    try { 
     outputStream.write(bytes); 
    } catch (IOException e) { } 
} 

//---call this from the main activity to 
// shutdown the connection--- 
public void cancel() { 
    try { 
     socket.close(); 
    } catch (IOException e) { } 
} 

} 

最後我用用Handler像這樣我接收到的數據:

static Handler UIupdater = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
     int numOfBytesReceived = msg.arg1; 
     byte[] buffer = (byte[]) msg.obj; 


     //---convert the entire byte array to string--- 
     //---extract only the actual string received--- 
     if(numOfBytesReceived>0) 
     { 
      strReceived = new String(buffer); 
      strReceived = strReceived.substring(0, numOfBytesReceived); 
     } 
     //---display the text received on the TextVie*--- 

    } 
}; 

這些代碼在TCP連接的罰款。我的問題是需要進行哪些更改才能將它們轉換爲UDP客戶端? 我想在AsyncTask中實現UDP,與我寫的TCP代碼相同。

回答

1

要使用UDP,您應該使用DatagramSocket

要發送消息:

DatagramSocket serverSocket = new DatagramSocket(); 
InetAddress IPAddress = InetAddress.getByName(ipAddress); 
byte[] sendData = message.getBytes(); 
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); 
serverSocket.send(sendPacket); 

要收到一條消息:

byte[] receiveData = new byte[15]; //max length 15. 
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
DatagramSocket clientSocket = new DatagramSocket(port); 
clientSocket.receive(receivePacket); 
String receivedMessage = new String(receivePacket.getData()).trim(); 
+0

我如何使用它完全像我寫的代碼TCP? (的AsyncTask) –

0

TCP & UDP之間的主要區別是,TCP是一個連接的套接字,你首先需要建立一個連接然後發送或接收數據包。 與UDP不同,您可以直接將數據包發送到IP +目的地端口,而無需以前的連接,它是一個未連接的套接字。

隨着UDP數據包的大小是有限的,建議不要超過512個字節,而不是用TCP還有的沒有限制。

使用UDP不能保證數據包會在另一邊接收,發送者不會有它是否收到任何確認,而不是在TCP有這樣的驗證。

如果你需要確保發送在另一側被接收的字節數,你需要使用TCP和UDP不

而且還知道,其實有些手機公司不分配任何更多的連接公共IP給客戶端,他們分配私有IP。在這種情況下,Android設備不能充當服務器,這意味着無法等待接收到的UDP數據包,並且由於其端口無法從WAN訪問而無法偵聽傳入的TCP連接。