2013-08-25 55 views
1

我有兩個類,一個發件人類,另一個是接收者類。發送和接收應用程序都在幾秒鐘後停止並關閉。 我的發件人類是:發送和接收數據報套接字上的UDP數據包android

public class MainActivity extends Activity { 
InetAddress receiverAddress; 
DatagramSocket datagramSocket; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    try { 
     datagramSocket = new DatagramSocket(4444); 
    } catch (SocketException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    byte[] buffer = "".getBytes(); 
    byte[] address="192.168.1.101".getBytes(); 

    try { 
     receiverAddress = InetAddress.getByAddress(address); 
    } catch (UnknownHostException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    DatagramPacket packet = new DatagramPacket(
      buffer, buffer.length, receiverAddress, 4444); 

    try { 
     datagramSocket.send(packet); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 




} 

我接收或聽力課是:事先的幫助

public class MainActivity extends Activity { 
DatagramSocket datagramSocket; 
DatagramPacket packet; 
TextView tv1; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    tv1=(TextView)findViewById(R.id.textView1); 
    try { 
     datagramSocket = new DatagramSocket(80); 
    } catch (SocketException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    byte[] buffer = new byte[10]; 
    packet = new DatagramPacket(buffer, buffer.length); 

    try { 
     datagramSocket.receive(packet); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    byte[] buff = packet.getData(); 

tv1.setText(buff.toString()); 

} 

感謝。

+1

我認爲你必須在單獨的線程或新線程上運行這些數據報事務,儘管我不確定這是否能解決你的問題 – kabuto178

+0

你的logcat中有什麼? –

回答

1

「新的DatagramSocket(...)」調用中的端口號看起來很奇怪。客戶端應該創建一個「未綁定」套接字 - 只需使用「new DatagramSocket();」。發送者應綁定到客戶端發送到的端口,即「新的DatagramSocket(4444);」。

+0

我認爲你的意思是「接收者」應該綁定到「發件人」發送到的端口。 – AlastairG

0

源和目標端口號應該相同。在「DatagramSocket(xxx)」中給出相同的數字。兩個程序中的xxx必須相同。

+0

幾乎但不完全。發件人的端口綁定無關緊要。在上面的代碼中,發送者正在發送到端口4444,並且接收者正在偵聽端口80. 這些都不能解釋爲什麼應用程序會在幾秒鐘後停止。接收機應該無限期地阻塞一個永遠不會到達的數據包。除非有人指着它的網頁瀏覽器... – AlastairG

2

在Android中你不能在UIThread(主線程)執行網絡運營

要解決這個問題: 您的網絡代碼複製到一個新的線程,並讓它運行。