简体   繁体   中英

Discover another device with TCP Socket Android

I have a client/server connection over tcp sockets in 2 android devices that are connected to the same wireless network, that uses an ip adress and a port, but what if the ip adress of both devices changes because of dhcp?, how can i do to discover the other device?

I think if only one of the ip changes i could tell the other device "this is my new ip", but if both changes that wouldn´t work, i am thinking in starting a loop from 192.168.1.1 to 192.168.1.255 and send the message with the new ip, i dont know if theres is a better way to do this, or which is the start and the end of the loop?

//SERVER
private void server() {
    ServerSocket serverSocket;
    Socket socket;
    try {
        serverSocket = new ServerSocket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(new InetSocketAddress(2222));

        while (true) {
            try {
                socket = serverSocket.accept();
                Runnable connection = new ConnectionHandler(socket);
                new Thread(connection).start();

            } catch (EOFException e) {

            } catch (Exception e) {

            }
        }

    } catch (IOException e) {

    } catch (Exception e) {

    }

}
public class ConnectionHandler implements Runnable {
    private Socket socket;
    public ConnectionHandler(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
            final String message = (String)input.readObject();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Message: " + message);
                    //Operate with message
                }
            });
            input.close();
            socket.close();
        } catch (IOException e) {
        } catch (ClassNotFoundException e) {
        }
    }
}

// CLIENT
public static synchronized void client(final String message, final String server_ip) {
    new Thread() {
        public void run() {
            Socket socket;
            try {
                ObjectOutputStream outputStream;
                SocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName(server_ip), 2222);

                socket = new Socket();                    
                socket.setReuseAddress(true);
                socket.setKeepAlive(true);
                socket.connect(socketAddress, 250);                    

                outputStream = new ObjectOutputStream(socket.getOutputStream());
                outputStream.flush();

                outputStream.writeObject(message);
                outputStream.flush();

                outputStream.close();
                socket.close();                    
            } catch (UnknownHostException e1) {

            } catch (IOException e1) {

            } 
        }
    }.start();
}

Since you are developing for Android. You can utilise android's WiFi direct implementation, which already includes peer discovery.

Once peer is discovered, you can initialized the connection and do whatever you intend to do, eg sending some data over. This part would be similar with what your existing code is doing.

Read the documentation here. http://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html

If one of the devices changes ip address your socket will break so you won't be able to send the new ip.

I think you should try implementing some udp broadcast server discovery.

Basicaly with udp discovery you would create an udp socket on your server. Each client will start by sending a broadcast udp message. The server will respond to taht message allowing the client to know the server ip address. When a socket break, you can just rediscover the host to update the server ip.

Take a look at kryonet . It's a nice and easy lib for networking in java. It has a built in host discovery so you can try using it. If you can't use it because you need to stay ontop of raw sockets or whatever reason, i suggest you take a look at kryonet's sources an copy the udp discovery part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM