javaandroidsocketsnetwork-programmingsocket-timeout-exception

Client-Server Program, can connect from Java client but not from Android


I have a working Java client/server program which is very straightforward and basic. This works fine. However, I am now trying to write an Android client, and I have been unable to connect to the server from my android client. I am using almost identical code for the android networking code as I use for the normal client. My android code is simple, all it does is starts this thread from onCreate:

private int serverPort = 8889;
private String serverIP = "192.168.5.230";
private Socket socket = null;

private Thread clientThread = new Thread("ClientThread") {
    @Override
    public void run() {
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(serverIP, serverPort), 1000);
            DataInputStream din = new DataInputStream( socket.getInputStream());
            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());

            while (true) {
                String message = din.readUTF();
                setPicture("picture1");
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
};

The port is the correct port my server is running on, as is the ip address (which I got from ifconfig since I know you cannot use localhost). When I run my normal pc client with the same port and IP address, the connection goes through. But when I run this code on my android device, the socket timesout when I try to connect.

Does anyone have any suggestions for where I am going wrong?


Solution

  • Double check that you added the permission requirement in the manifest file:

    <uses-permission android:name="android.permission.INTERNET" />
    

    But, possibly more importantly, 192.168.x.x is a local or non-routable network so you need to be on the same network, or one that knows how to reach the 192.168.5.230 address. You say that it doesn't work when you try it on your device -- are you running on local wifi when you run or are you on your mobile network? If you're on mobile, try it from wifi.