ssk
ssk

Reputation: 9265

DatagramSocket fails on Android with 'Try Again'

I am trying to send DatagramPackets (UDP) in my Android application:

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

I get the following error:

Try again

Am I missing something here?

Upvotes: 1

Views: 1312

Answers (1)

David Kroukamp
David Kroukamp

Reputation: 36423

Well to send the UDP you'd need something similar to:

Server:

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

Client:

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

References:

Upvotes: 1

Related Questions