Ben__F
Ben__F

Reputation: 13

Java Open socket getting Connection Refused attempting to connect to localhost server

I'm running a simple test server on my PC. The server is written in Python and it seems to work, sitting there listening on Port 8048 and just sending back messages to show what it has received. I can test the server using Putty and it seems to be good (if I choose Raw connection).

This is all about testing a client program written in Java which I'm running on an Android Emulator on the PC: Emulator Nexus_5X_API_27 Android 8.1.0. I have a working version of the client program written in Python, but I need to make it into an android app now, hence the Java.

This is my first time with Java and I'm using Android Studio. The try...catch block shows that something goes wrong when creating the socket. I've read all of the questions and answers about "Connection Refused" errors and I believe that I've checked for all the common causes (server not running, wrong port, firewall).

This is what the test server looks like:

import socket, threading, time      
global remote_command, remote_reply

def listen():
    global server
    global remote_command, remote_reply

    soc = socket.socket() # Create a socket object
    host = "localhost"  
    port = 8048             
    soc.bind((host, port))       
    soc.listen(5)              
    while True:
        conn, addr = soc.accept()     # Wait for client.
        print ("Got connection from",addr)
        remote_command = conn.recv(1024)

        while remote_command:
           time.sleep(0.1)   # pause this while the main thread processes and clears the remote_command
        conn.send( remote_reply)
        remote_reply = ""

thread = threading.Thread(target = listen)
thread.start()
remote_command = ""
while True:
    if remote_command:
        print remote_command
        remote_reply = "I received " + remote_command
        remote_command = ""

The Java client relevant part is:

public class doLogin {
    String output;
     public doLogin( final java.lang.String ip, final java.lang.String LoginName) {
        final String sessionID = randomAlphaNumeric(10);
        textView = (TextView) (findViewById(R.id.editText));
        Log.d("Debug", "in doLogin for " + LoginName);

        AsyncTask.execute(new Runnable() {

            @Override
            public void run() {
                Socket loginSocket = null;
                BufferedReader in;
                //PrintWriter out;
                DataOutputStream out;
                Log.d("Debug","in AsyncTask " + ip);
                try {
                    Log.d("Debug","About to create socket IP: " + ip );
                    loginSocket = new Socket(ip, 8048);
                    ...
                    ...
                } catch (IOException e) {
                    System.err.println("Couldn't get I/O for the connection to: " + ip + " " + e.getMessage());

If anyone can see what I've done wrong, I would be immensely grateful! The error logged is: 12-18 21:38:20.819 10792-10827/com.example.ben.heatingcontroller W/System.err: Couldn't get I/O for the connection to: 127.0.0.1 failed to connect to /127.0.0.1 (port 8048) from /:: (port 39437): connect failed: ECONNREFUSED (Connection refused)

Upvotes: 1

Views: 1896

Answers (2)

greenapps
greenapps

Reputation: 11224

Use 10.0.2.2 as ip address if your client app, running on an emulator, tries to connect to a server on the same pc as your emulator is running on.

Upvotes: 1

stdunbar
stdunbar

Reputation: 17545

The Android emulator is a virtual machine and so "localhost" isn't the same local host as your server. I would recommend two changes:

  1. Change the host name in your server from localhost to the IP address of your PC. This is probably something like 192.168.x.y but validate that by running ipconfig /all (I guessed Windows O/S - the commands are much different in the Unix/Mac O/S world) in a command line window. You may get a ton of output but one adapter should have an IPv4 Address that makes sense.
  2. In your Android environment connect to that same IP address.

Upvotes: 0

Related Questions