Unknown BL4NK
Unknown BL4NK

Reputation: 15

socket connection without server using internet

I'm going to set a simple socket connection between two android devices using internet. There are two devices and two android app's , one of them is client app and another is server app. When the apps run on a device it's all OK, but when the apps run on two devices the client application doesn't connect to server application.

Client app:

btnSend.setOnClickListener(view -> {
        String msg = etMessage.getText().toString();
        AsyncTask.execute(() -> {
            try {
                DatagramSocket socket = new DatagramSocket();
                InetAddress ip = InetAddress.getByName("100.66.20.245");
                int port = 1020;
                DatagramPacket packet = new DatagramPacket(
                        msg.getBytes(), msg.length(), ip, port
                );
                socket.send(packet);
                runOnUiThread(() -> {
                    Toast.makeText(this, "Message sent", Toast.LENGTH_SHORT).show();
                });
            } catch (Exception e) {
                Log.w(TAG, e.toString());
            }
        });
});

Server app:

Runnable runnable = () -> {
        try {
            int port = 1020;
            DatagramSocket socket = new DatagramSocket(port);
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,1024);
            runOnUiThread(() -> {
                Toast.makeText(this,"Waiting for client",Toast.LENGTH_SHORT).show();
            });
            socket.receive(packet);
            String msg = new String(packet.getData(),0,packet.getLength());
            runOnUiThread(() -> {
                Toast.makeText(this, "Client msg : " + msg, Toast.LENGTH_SHORT).show();
            });
        } catch (Exception e) {
            Log.w(TAG, e.toString());
        }
};
new Thread(runnable).start();

Upvotes: 0

Views: 1110

Answers (2)

Unknown BL4NK
Unknown BL4NK

Reputation: 15

The best solution was the port forwarding with a router.
When you are using a router you can set an ip address to forwarding ports to that ip address. However if you have a better solution, please post a comment :)

Upvotes: 0

Abolhassan Pirayeh
Abolhassan Pirayeh

Reputation: 104

Are both devices connected to a network? And is the IP address of client application equal to the IP address of the server?

Upvotes: 1

Related Questions