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)
AsyncTask.execute(new Runnable() {. Strange code. Did you invent that yourself?