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)?