I'm trying to do a very simple client on android to send an UDP message to a server on Android.
Here's my simple UDP client:
public class MyUDPClient {
private static String TAG = "MyUDPClient";
private DatagramSocket udpSocket;
private InetAddress serverAddress;
private int port;
private Scanner scanner;
public MyUDPClient(String destinationAddr, int port) throws SocketException, UnknownHostException {
this.serverAddress = InetAddress.getByName(destinationAddr);
this.port = port;
udpSocket = new DatagramSocket(this.port);
scanner = new Scanner(System.in);
}
public void send(String message) throws IOException {
DatagramPacket p = new DatagramPacket(
message.getBytes(), message.getBytes().length, serverAddress, port);
Log.d(TAG, "udp client send: " + message + " to serverAddress " + serverAddress);
this.udpSocket.send(p);
}
public void connect() {
Log.d(TAG, "UDP connection to port " + port);
}
}
And here's my simple UDP server:
public class MyUDPServer {
private String TAG = "MyUDPServer";
private int port;
private DatagramSocket udpSocket;
OnMessageCallback onMessageCallback;
public MyUDPServer(int port) throws SocketException {
this.udpSocket = new DatagramSocket(port);
this.port = port;
}
public interface OnMessageCallback {
public void on(String message);
}
private void listen() throws Exception {
Log.d(TAG, "listening UDP server on port " + port);
String msg;
while (true) {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
// blocks until a packet is received
udpSocket.receive(packet);
msg = new String(packet.getData()).trim();
Log.d(TAG, "message received; " + msg);
onMessageCallback.on(msg);
}
}
public void start() throws Exception {
listen();
}
public void setMessageCallback(OnMessageCallback onMessageCallback) {
this.onMessageCallback = onMessageCallback;
}
}
The problem is that the server never receives any messages. I start the client like this:
MyUDPClient myUDPClient = new MyUDPClient("192.168.1.6", 8887);
Since it's on an emulator, I try to filter the IP 192.168.1.6
and even though I call myUDPClient.send("message")
, on WireShark I receive nothing, which indicates that the message is not even leaving the computer where the emulator tuns.
What am I doing wrong?
I've created a WebSocket client/server on Android and it worked fine.
I have these 2 permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />