简体   繁体   English

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

[英]Why my app can't connect to socket.io server?

my friend, I want to connect my application to the socket.io node.js webserver and this is my mobile side code:我的朋友,我想将我的应用程序连接到 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();
    }

And this is my webserver code:这是我的网络服务器代码:

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;

And when I run my mobile app project, I got this error:当我运行我的移动应用程序项目时,我收到了这个错误:

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

And also I searched a lot about it and I added internet permission in the manifest file:我也搜索了很多关于它的内容,并在清单文件中添加了互联网权限:

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

And I added usesCleartextTraffic in the manifest file and inside the application tag:我在清单文件和应用程序标记中添加了 usesCleartextTraffic:

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

This is all of my logcat:这是我的全部日志:

    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}

But I still get this error please help me.但我仍然收到此错误,请帮助我。

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

add this to your manifest将此添加到您的清单中

and please post all logcat message并请发布所有 logcat 消息

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

Change HTTPS to HTTP I hope it helps The problem is not so clear but try this and tell me if it works将 HTTPS 更改为 HTTP 我希望它有帮助 问题不太清楚,但试试这个并告诉我它是否有效

And try to put this object并尝试把这个 object

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

To this对此

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM