简体   繁体   English

Android Node.js Socket.io 未连接

[英]Android Node.js Socket.io not connecting

I have a Node.js server using socket.io and an android app.我有一个使用 socket.io 的 Node.js 服务器和一个 android 应用程序。 I want my app to connect to the server.我希望我的应用程序连接到服务器。 (I work locally) (我在当地工作)

So first I start the server : command prompt所以首先我启动服务器:命令提示符

Here is the code of it :这是它的代码:

var express    = require('express');        // call express
var app        = express();  
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 1234;


app.get('/',function(req,res){
    res.send("Welcome to my socket");
});


io.on('connection', function (socket) {

    console.log('one user connected : '+socket.id);

    // when the client emits 'new message', this listens and executes
    socket.on('new message', function (data) {
        // we tell the client to execute 'new message'
        console.log('this is message :',data);
    });

});


http.listen(port, function () {
  console.log('Server listening at port %d', port);
});

And then I try to connect from my activity here :然后我尝试从这里的活动连接:

public class AvisActivity extends AppCompatActivity {

  private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://172.21.191.234:1234");
        } catch (URISyntaxException e) { Log.v("AvisActivity", "error connecting to socket");}
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_avis);


        Log.v("AvisActivity", "try to connect");
        mSocket.connect();
        Log.v("AvisActivity", "connection sucessful");

    }
}

My problem is that I never see the log "one user connected" on the server but I always see the "try to connect" and " connection sucessful" on the android log.我的问题是我从未在服务器上看到“一个用户已连接”的日志,但我总是在 android 日志上看到“尝试连接”和“连接成功”。

Can someone solve this mystery for my please ?有人可以为我解开这个谜吗?

UPDATE更新

My code worked fine, but I encounter some Wifi configuration that blocks web socket (and actually my school did, that's where my problems came from)我的代码运行良好,但我遇到了一些阻止网络套接字的 Wifi 配置(实际上我的学校做到了,这就是我的问题所在)

In the latest versions of Android, you need to add AndroidManifest.xml "android: usesCleartextTraffic = true" to allow connections with plain text.在最新版本的Android中,您需要添加AndroidManifest.xml "android: usesCleartextTraffic = true" 以允许纯文本连接。

Example:例子:

<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"
    android:usesCleartextTraffic="true">

Android Developers > Docs > Guías - Link Android 开发者 > 文档 > Guías - 链接

对于 API 23 及更高版本,您必须在清单文件中添加android:usesCleartextTraffic="true"

For anyone else googling here, this helped me get some log information about the problem:对于在这里使用谷歌搜索的其他人,这帮助我获得了有关该问题的一些日志信息:

Log.v("AvisActivity", "try to connect");
mSocket.connect();

mSocket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        Transport transport = (Transport) args[0];
        transport.on(Transport.EVENT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Exception e = (Exception) args[0];
                Log.e(TAG, "Transport error " + e);
                e.printStackTrace();
                e.getCause().printStackTrace();
            }
        });
    }
});

For me, the issue is that the client won't use TLSv1.1 or 1.2.对我来说,问题是客户端不会使用 TLSv1.1 或 1.2。 I haven't figured it out as of this writing.在写这篇文章的时候我还没有弄清楚。 Making my server support TLSv1.0 is my current workaround.让我的服务器支持 TLSv1.0 是我目前的解决方法。

Put your socket initializing code inside your onCreate method like below:将您的套接字初始化代码放在您的onCreate方法中,如下所示:

public class AvisActivity extends AppCompatActivity {

  private Socket mSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_avis);

        try {
            mSocket = IO.socket("http://172.21.191.234:1234");
        } 
        catch (URISyntaxException e) { 
            Log.v("AvisActivity", "error connecting to socket");
        }

        Log.v("AvisActivity", "try to connect");
        mSocket.connect();
        Log.v("AvisActivity", "connection sucessful");

    }
}

you code is fine it's working properly, you need to only confirm IP address which you are connecting is right and also INTERNET permission added in manifest.xml你的代码很好,它工作正常,你只需要确认你连接的 IP 地址是正确的,并且在 manifest.xml 中添加了 INTERNET 权限

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

在此处输入图片说明

UPDATE更新

My code worked fine, but I encounter some Wifi configuration that blocks web socket (and actually my school did, that's where my problems came from).我的代码运行良好,但我遇到了一些阻止 Web 套接字的 Wifi 配置(实际上我的学校做到了,这就是我的问题所在)。 But I don't really know how they blocked it.但我真的不知道他们是如何阻止它的。

Also, later in my project when I deploy to an OVH server, I got problems by using the 1234 port.此外,稍后在我的项目中,当我部署到 OVH 服务器时,我在使用 1234 端口时遇到了问题。 Make sure to use a port available/unlocked by your provider.确保使用您的提供商可用/解锁的端口。

Check out this answer, worked for me with this single line:看看这个答案,用这一行对我有用:

opts.transports = new String[]{"websocket"}; opts.transsports = new String[]{"websocket"};

https://stackoverflow.com/a/67978895/6909832 https://stackoverflow.com/a/67978895/6909832

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

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