android - 无法在本地连接 Android 中的 web-socket 客户端
问题描述
我们正在尝试在android中实现webSocket,连接从未建立。但这与本机反应很好,任何人都可以帮助我们,谢谢。
即使我尝试使用 socket.io 和 okHttp3,我也可能会错过一些配置。
这是我的 MainActivity 文件
package com.example.client_app;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.net.URI;
import java.net.URISyntaxException;
import tech.gusavila92.websocketclient.WebSocketClient;
public class MainActivity extends AppCompatActivity {
private WebSocketClient webSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createWebSocketClient();
}
private void createWebSocketClient() {
URI uri;
try {
// Connect to local host
uri = new URI("ws://192.168.21.133:8080");
}
catch (URISyntaxException e) {
e.printStackTrace();
return;
}
webSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen() {
Log.i("WebSocket", "Session is starting");
webSocketClient.send("Hello World!");
}
@Override
public void onTextReceived(String s) {
Log.i("WebSocket", "Message received");
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
try{
// TextView textView = findViewById(R.id.animalSound);
// textView.setText(message);
} catch (Exception e){
e.printStackTrace();
}
}
});
}
@Override
public void onBinaryReceived(byte[] data) {
}
@Override
public void onPingReceived(byte[] data) {
}
@Override
public void onPongReceived(byte[] data) {
}
@Override
public void onException(Exception e) {
Log.d("WebSocket", "Closed ");
System.out.println(e.getMessage());
}
@Override
public void onCloseReceived() {
Log.i("WebSocket", "Closed ");
System.out.println("onCloseReceived");
}
};
webSocketClient.setConnectTimeout(10000);
webSocketClient.setReadTimeout(60000);
webSocketClient.enableAutomaticReconnection(5000);
webSocketClient.connect();
}
}
这是我的 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.client_app">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
还有我的 gradle 文件
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.client_app"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-
rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'tech.gusavila92:java-android-websocket-client:1.2.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
最后是我的节点服务器文件
const express = require('express'); // using express
const socketIO = require('socket.io');
const http = require('http')
const port = process.env.PORT||8080 // setting the port
let app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
let server = http.createServer(app)
let io = socketIO(server)
// make connection with user from server side
io.on('connection', (socket)=>{
console.log('New user connected');
//emit message from server to user
socket.emit('newMessage', {
from:'jen@mds',
text:'hepppp',
createdAt:123
});
// listen for message from user
socket.on('createMessage', (newMessage)=>{
console.log('newMessage', newMessage);
});
// when server disconnects from user
socket.on('disconnect', ()=>{
console.log('disconnected from user');
});
});
io.on('onOpen', (socket)=>{
console.log('onOpen-----------');
});
app.use('/api', router);
// my local ip
server.listen(port, '192.168.21.133', () => {
console.log("app working", port)
});
解决方案
你的操作系统有一个 localhost,所以你可以访问 http://localhost:8000。但是android也有一个本地主机。因此,当您的应用程序转到 localhost 时,它会在 android 模拟器中搜索该 url,您需要离开那里并进入开发计算机 localhost。我所做的是将我的节点应用程序部署在 heroku 测试服务器中,仅此而已。
此外,正如 M.Pomeroy 在下面的评论中所说,您可以使用特殊 ip 10.0.2.2 访问开发机器,我错过了该信息。
推荐阅读
- xml - XSD 到 XML 转换器
- javascript - Echobot 在 Line 上不起作用(不响应消息)
- c++ - 从文本文件c ++填充对象
- powershell - 有条件地将输出写入文件以跟踪 pourposes
- c# - Uri 方案太长 – AppSettings.config
- database - 从 Oracle 云存储读取数据到目标数据库
- c# - 如何查找 String 中是否有特殊字符?前任 : ” ] ”
- git - 我可以从不同的分支中挑选多个提交吗?
- apache-nifi - 如何使用 Apache Nifi 将数据从 HDFS 传输到 Oracle?
- angular - Angular:将类型字符串返回到 catchError 但具有不同类型的 HTTP