为什么我的应用无法连接到 socket.io 服务器?

时间:2021-02-08 05:59:18

标签: java android node.js android-studio socket.io

我的朋友,我想将我的应用程序连接到 socket.io node.js 网络服务器,这是我的移动端代码:

    private Socket mSocket;

    try {
        IO.Options options = new IO.Options();
        options.forceNew = true;
        options.transports = new String[]{WebSocket.NAME};

        mSocket = IO.socket("https://taxiappapi.webfumeprojects.online", options);
        mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
                    }
                });
                Log.d(TAG, "Socket checkConnection: connect 1 " + args[0]);
            }
        });

        mSocket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "Connection error!", Toast.LENGTH_SHORT).show();
                    }
                });
                Log.d(TAG, "Socket checkConnection: onConnectError 1 " + args[0]);
            }
        });

        mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "Connection timeout!", Toast.LENGTH_SHORT).show();
                    }
                });
                Log.d(TAG, "Socket checkConnection: onConnectTimeOut 1 " + args[0]);
            }
        });

        mSocket.connect();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

这是我的网络服务器代码:

const express = require("express");
var ObjectId = require('mongoose').Types.ObjectId;
const ioAuth = require("../../middleware/socketAuth");
const Driver = require("../../model/driver/userDriver");
const app = express.Router();
const http = require('http').Server(app);
const io = require('socket.io')(http, {
  cors: {
    origin: "http://localhost:4200",
    methods: ["GET", "POST"]
  }
});
io.on('connection', (socket) => {
  console.log('a user connected');
  // Auth
    // io.use((socket, next) => {
    //     ioAuth(socket, next);
    //     // const token = socket.handshake.auth.token;
    //     // console.log(token);
    //     // if(token == 'abc'){
    //     //     next();
    //     // }else{
    //     //     const err = new Error("not authorized");
    //     //     err.data = { content: "Please retry later" }; // additional details
    //     //     next(err);
    //     // }
    // });
  socket.on("online", (arg) => {
    if(ObjectId.isValid(arg.driver)){
        let isOnline = arg.status;
        Driver.findByIdAndUpdate(arg.driver, {isOnline: isOnline}, function(err, data){
          if(err) console.log(err); // world.
          console.log(data); // world.
          console.log(arg.driver + ' now is ' + isOnline); // world.
          socket.emit(arg.driver,  'My New Location: ' + arg.status);
        });
    }else{
        console.log('not an object ID', arg)
    }
  });
  socket.on("MyLocation", (arg) => {
    if(ObjectId.isValid(arg.driver)){
        let lat = arg.lat;
        let lng = arg.lng;
        let location = {
            type: "Point",
            coordinates: [
                lat, lng
            ]
        };
        Driver.findByIdAndUpdate(arg.driver, {location});
        console.log(arg.driver + ' now is ' + arg.status); // world.
        socket.emit(arg.driver,  arg);
    }else{
        console.log('not an object ID')
    }
  });
  socket.on("MyID", (arg) => {
    console.log(arg); // world
  });
});
http.listen(3100, () => {
  console.log('listening on *:3100');
});
// // server.listen(3100);
module.exports = app;

当我运行我的移动应用项目时,我收到了这个错误:

io.socket.engineio.client.EngineIOException: websocket error

我还搜索了很多关于它的内容,并在清单文件中添加了互联网权限:

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

我在清单文件和应用程序标签中添加了 usesCleartextTraffic :

<application
    android:usesCleartextTraffic="true"...

这是我所有的日志:

    D/Surface: Surface::disconnect(this=0x7de6832000,api=1)
D/View: [Warning] assignParent to null: this = android.widget.LinearLayout{ca34e7f V.E...... ......ID 0,0-574,316}
I/System.out: [socket]:check permission begin!
W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
I/System.out: [socket] e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaUtils
D/MAHDI: Socket checkConnection: onConnectError 1 io.socket.engineio.client.EngineIOException: websocket error
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.example.myapplication activity: com.example.myapplication.MainActivity@840a557
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.example.myapplication activity: com.example.myapplication.MainActivity@840a557
D/ViewRootImpl[Toast]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
I/Toast: Show toast from OpPackageName:com.example.myapplication, PackageName:com.example.myapplication
E/GraphicExt: GraphicExtModuleLoader::CreateGraphicExtInstance false
D/Surface: Surface::connect(this=0x7de6832000,api=1)
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
D/Surface: Surface::setBufferCount(this=0x7de6832000,bufferCount=3)
D/Surface: Surface::allocateBuffers(this=0x7de6832000)
D/Surface: Surface::disconnect(this=0x7de6832000,api=1)
D/View: [Warning] assignParent to null: this = android.widget.LinearLayout{ec79f11 V.E...... ......ID 0,0-574,316}

但我仍然收到此错误,请帮助我。

2 个答案:

答案 0 :(得分:0)

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

将此添加到您的清单

并请发布所有 logcat 消息

答案 1 :(得分:0)

将 URL 编辑为 http://taxiappapi.webfumeprojects.online

将 HTTPS 更改为 HTTP 我希望它有帮助问题不太清楚,但试试这个并告诉我它是否有效?

并尝试放置这个对象

io.on('connection', (socket) => .....

为此

(async () => {
  io.on('connection', (socket) =>
  //And the http.listen too.
})()