0

我已经实现了 socket.io 网站中提到的每个步骤,但不确定为什么我无法从我的 Android 应用程序连接到 Node.js 服务器。以下是我用于实现的文件。

包.json

{
    "name": "First application"
    "version": "1.0.0",
    "description": "My First Android Application",
    "main": "server.js",
    "dependencies": {
        "express": "^4.17.1",
        "socket.io": "^2.3.0"
        "socket.io-client": "^2.3.0"        
    }
}

Index.js(服务器文件)

var app=require('express')();
var server=require('http').createServer(app);
var io=require('socket.io')(server);

app.get('/',(req,res) => {
    res.send('Server is running on port 3000');
});

io.on('connection',(socket) => {
    console.log('Device connected');
    socket.on('foo',(request) => {
        console.log('Received foo from host');
    });
});

server.listen(3000,() => {
    console.log('listening to port:3000');
});

客户端代码

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class MainActivity extends AppCompatActivity {

    Socket socket;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            socket = IO.socket("http://192.168.xx.xx:3000/");
            socket.on(Socket.EVENT_CONNECT,  new Emitter.Listener() {

                @Override
                public void call(Object... args) {
                    Log.d("TAG", "Socket Connected!");
                }

            });

            Log.d("socket status",String.valueOf(socket.connected()));
        }
        catch (URISyntaxException e){
            e.printStackTrace();
        }
}
}

build.gradle(: app) 添加到 Gradle 依赖项的下面部分

    implementation ('io.socket:socket.io-client:1.0.0'){
        exclude group: 'org.json',module:'json'
    }
  1. 我可以通过手机访问 192.168.xx.xx:3000。手机和笔记本电脑在同一个wifi网络。
  2. Socket.connected() 返回 false。
  3. “插座已连接!” 也没有被记录。让我知道是否需要进行其他分析。
4

0 回答 0