2012-07-23 71 views
1

我想在我的Android應用程序中發送DatagramPackets(UDP):DatagramSocket的Android上失敗, '再試一次'

//create a byte to receive data 
mClientSocket = new DatagramSocket(); 
byte[] receiveData = new byte[MAX_RECEIVE_DATA_SIZE_BYTES]; 
DatagramPacket receivePacket = new DatagramPacket(receiveData, 
     receiveData.length); 

// Set a receive timeout 
mClientSocket.setSoTimeout(timeout); 

// receive the packet 
mClientSocket.receive(receivePacket); 

return new String(receivePacket.getData(), 0, 
     receivePacket.getLength()); 

我收到以下錯誤:

Try again

我缺少的東西這裏?

回答

1

好發送UDP你需要類似於:

服務器:

String messageStr="Hello Android!"; 
int server_port = 12345; 
DatagramSocket s = new DatagramSocket(); 
InetAddress local = InetAddress .getByName("192.168.1.102"); 
int msg_length=messageStr.length(); 
byte[] message = messageStr.getBytes(); 
DatagramPacket p = new DatagramPacket (message, msg_length,local,server_port); 
s.send(p); 

客戶:

String text; 
int server_port = 12345; 
byte[] message = new byte[1500]; 
DatagramPacket p = new DatagramPacket (message, message.length); 
DatagramSocket s = new DatagramSocket (server_port); 
s.receive(p); 
text = new String (message, 0, p.getLength()); 
Log.d("Udp tutorial","message:" + text); 
s.close(); 

參考文獻:

+0

大衛你好。在客戶端,我在網絡中有一些控制器。我通過其他程序(串行和網絡工具)測試信號。但沒有從我的應用程序發送UDP。 catch(Exception e) android.util.Log.w(「UDP」,「Catched here 4」); e.printStackTrace(); }此代碼適用於 – 2015-11-05 13:41:47

+0

請幫忙。哪些問題可能是。我是Android的初學者 – 2015-11-05 13:43:43

相關問題