Android Node.js Socket.io 未连接

标签 android node.js sockets socket.io connection

我有一个使用 socket.io 的 Node.js 服务器和一个 Android 应用程序。我希望我的应用程序连接到服务器。 (我在本地工作)

所以首先我启动服务器: command prompt

这是它的代码:

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);
});

然后我尝试通过我在这里的 Activity 进行连接:

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");

    }
}

我的问题是我从来没有在服务器上看到“一个用户已连接”的日志,但我总是在 android 日志上看到“尝试连接”和“连接成功”。

有人能帮我解开这个谜团吗?

更新

我的代码运行良好,但我遇到了一些阻止网络套接字的 Wifi 配置(实际上我的学校确实如此,这就是我的问题所在)

最佳答案

在最新版本的Android中,需要在AndroidManifest.xml中添加“android:usesCleartextTraffic = true”以允许纯文本连接。

例子:

<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 Node.js Socket.io 未连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34271106/

相关文章:

android - 在布局 onClick 之间来回移动以编程方式添加的 TextView

android - 具有不同数据的新警报覆盖已设置的警报

javascript - v8::HandleScope::CreateHandle() 中的 fatal error # 无法在没有 HandleScope 的情况下创建句柄

javascript - 关于自己的 REST API 和使用 3rd 方 API 获取的问题

node.js express集群和高CPU使用率

android - 部署 Xamarin Forms Android 应用程序时内存不足

android - 使用 Facebook SDK 4 (Android) 的自定义按钮

c# - 系统.Net.WebException : Unable to connect to Remote Server - Server in LAN only

c - 在反向 shell 中打印当前目录

java - SocketChannel 读取时 CPU 负载较高