无法在本地连接Android中的网络套接字客户端

时间:2020-01-24 11:14:10

标签: android websocket socket.io okhttp

我们正在尝试在android中实现webSocket,但从未建立连接。但这可以与react-native配合使用,任何人都可以以同样的感谢帮助我们。

即使我尝试使用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)
}); 

1 个答案:

答案 0 :(得分:1)

您的操作系统有一个localhost,因此您可以访问http:// localhost:8000。但是android也有一个本地主机。因此,当您的应用程序转到localhost时,它将在android仿真器中搜索该url,您需要离开那里并进入开发计算机localhost。那很复杂,我要做的是将我的节点应用程序部署在heroku测试服务器中,就是这样。