0

I need to send messages from a Java program on my PC to an Android Wear 2.0 app. The watch is directly (no intermediate phone) connected to a mobile hotspot (default hotspot setup by Windows 10 settings) on the PC that I want to send the messages from. Wifi adb debugging happens flawless over this local network.

The goal is a one-to-one communication, so I worked with simple Java Networking sockets. The laptop acts as server, the watch as client. On the wear app, this happens in a seperate AsyncTask:

@Override
protected Void doInBackground(Void... voids) {
    try(Socket audioSocket = new Socket("localhost",4445);
        PrintWriter out = new PrintWriter(audioSocket.getOutputStream(),true);
        BufferedReader in = new BufferedReader(new InputStreamReader(audioSocket.getInputStream()));){
        while(true){
            String msg = in.readLine();
            // do something with msg
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

On the Java PC application, the server also runs in a seperate thread:

@Override
public void run() {
    ServerSocket serverSocket = new ServerSocket(4445);
    while (true) {
        try(Socket clientSocket = serverSocket.accept()) {
            try(PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {
                while (true) {
                    // send messages
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(AudioServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

In the manifest of the wear app, I ask for the following permission:

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

The Java PC application runs fine. However, when I run the wear app, I get the following error:

System.err: java.net.ConnectException: Connection refused

What is the reason for this error? Or is there a better way to have a one-to-one communication between wearable and PC application (security isn't important in this case)?

Michael Troger
  • 3,336
  • 2
  • 25
  • 41
J.A.
  • 1
  • 1
  • Have you check if: 1) You are trying to connect to the wrong IP/port. 2)You have not started your server. 3) Your server is not listening for connections. 4) On Windows servers, the listen backlog queue is full.? Reference: [SO post](https://stackoverflow.com/questions/6876266/java-net-connectexception-connection-refused) – MαπμQμαπkγVπ.0 Mar 16 '18 at 11:13
  • The problem was indeed the wrong IP address: it had to be `192.168.137.1` (Windows hotspot IP address) instead of `localhost`. – J.A. Mar 16 '18 at 12:47

1 Answers1

0

I found the solution myself: I changed localhost to 192.168.137.1, the default IP-address of the Windows hotspot.

J.A.
  • 1
  • 1