MisterL2
MisterL2

Reputation: 161

Java Sockets not working on Android (ECONNREFUSED)

When trying to connect to a socket with an Android client, I receive ECONNREFUSED ConnectException.

When I run the code on my PC, it works fine I am able to connect to the remote server (raspberry pi, haskell) without an issue (so we can exclude that possibility).

Relevant code from ConnectionManager.class (Error thrown in line s=connect):

    @Override
    protected void onHandleIntent(Intent intent) {
    try {
        s=connect();
        socket_out = new PrintWriter(s.getOutputStream(), true);
        socket_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The connect function (error thrown in line "return new socket")

    private Socket connect() {
    try {
        return new Socket("Thereisarealip in here",Realport);
    } catch (IOException ex) {
        Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    throw new RuntimeException();
}

XML Permissions include the following

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

The ConnectionManager Java class is called from the mainthread using:

    Intent intent = new Intent(this, ConnectionManager.class);
    startService(intent);

Upvotes: 0

Views: 1635

Answers (2)

MisterL2
MisterL2

Reputation: 161

Found the issue. The router did not allow any mobile devices in the wifi network to access static IP addresses, but instead redirected them to a custom page without throwing an error.

Upvotes: 1

Ryosuke
Ryosuke

Reputation: 3892

ECONNREFUSED is only thrown when the server is either not listening on the specified port or it is not able to handle the request. Make sure that your server is able to receive connections continuously. For that listen for incoming connections on one thread and handle them on other thread without blocking the listening process. As I can see the INTERNET permission is already declared in the manifest so the problem can only be on server side.

Upvotes: 1

Related Questions