[英]Network messaging from Java PC application to Android Wear 2.0 app
I need to send messages from a Java program on my PC to an Android Wear 2.0 app. 我需要从PC上的Java程序向Android Wear 2.0应用发送消息。 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.
手表直接(没有中间电话)连接到要从其发送消息的PC上的移动热点(Windows 10设置为默认热点设置)。 Wifi adb debugging happens flawless over this local network.
Wifi adb调试可以在此本地网络上进行。
The goal is a one-to-one communication, so I worked with simple Java Networking sockets. 目标是一对一的通信,因此我使用了简单的Java Networking套接字。 The laptop acts as server, the watch as client.
笔记本电脑充当服务器,手表充当客户端。 On the wear app, this happens in a seperate AsyncTask:
在Wear应用上,这发生在单独的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: 在Java PC应用程序上,服务器还运行在单独的线程中:
@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: 在Wear应用的清单中,我要求获得以下许可:
<uses-permission android:name="android.permission.INTERNET" />
The Java PC application runs fine. Java PC应用程序运行良好。 However, when I run the wear app, I get the following error:
但是,当我运行Wear应用程序时,出现以下错误:
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)?
还是有更好的方法在可穿戴设备和PC应用程序之间进行一对一通信(在这种情况下,安全性并不重要)?
我自己找到了解决方案:我将localhost
更改为Windows热点的默认IP地址192.168.137.1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.