1

我正在尝试DatagramPackets在我的 Android 应用程序中发送(UDP):

//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());

我收到以下错误:

再试一次

我在这里错过了什么吗?

4

1 回答 1

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

参考:

于 2012-07-23T17:54:36.063 回答