简体   繁体   中英

Establishing a connection between Java server and client within Android appEDIT

I have an app in android in which I created an android client and a Java sever.

But I'm confronting the following issue: my client (the android part) connects to the local machine on port 6000 using the android loopback address.

My server (in Java) listens on local machine at the port 6000 - but what is the IP I have to use to get the socket that accepts the clients?

InetSocketAddress serverAddr = new InetSocketAddress(SERVERIP,serverPort);
serverSocket = new ServerSocket();
serverSocket.bind(serverAddr);

So what is the SERVERIP I have to use?

UPDATE:My client runns on an emulator!!!!!

EDIT:

public class ClientThread implements Runnable { Object syncToken;

    public ClientThread(Object syncToken) {
        this.syncToken = syncToken;
    }

    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);

            socket = new Socket(serverAddr, 50458);


        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
        } catch (IOException e) {
            System.err
                    .println("Couldn't get I/O for the connection to host");
        }

        try {
            out = new PrintStream(socket.getOutputStream());
        } catch (IOException e) {

            System.out.println(e);
        }

        while (true) {
            synchronized (syncToken) {
                try {
                    syncToken.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

And here is: private String serverIpAddress = "10.0.2.2";!!!!!

From http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking : if you want to communicate from within the emulator to the local host, use IP 127.0.0.1 on the local host and use IP 10.0.2.2 in Android. This should let you communicate between the Android client and the local host server.

You want to run the server part on the Android? I guess not, and in such case using loopback address is not really going to work, as loopback interface on the Android system loops back to the Android machine itself, it is not routed to the outside.

For the serverAddr, use the #InetSocketAddress(int port) constructor, it specifies the wildcard address and a specific port, meaning it listens on all the interfaces of the machine.

Edit: For best results, on the android device use the DNS name of the server to connect to it.

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