因此,在这里,我尝试使用socket.io将我的android连接到服务器node.js,但是在执行过程中,没有错误,但尚未建立连接,并返回false
预先感谢您的帮助!
Socket.Java
package com.example.myprojectapplication.ObjectClass;
import com.github.nkzawa.socketio.client.IO;
import java.net.URISyntaxException;
public class Socket {
private com.github.nkzawa.socketio.client.Socket mSocket;
{
try {
mSocket = IO.socket("localhost:8081/");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public com.github.nkzawa.socketio.client.Socket getSocket() {
return mSocket;
}
}
我的MainActivity的相关部分
com.example.myprojectapplication.ObjectClass.Socket app = new com.example.myprojectapplication.ObjectClass.Socket();
Socket mSocket = app.getSocket();
mSocket.connect();
Node.js服务器
var mysql = require('mysql');
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('message', 'Android Connected');
console.log("Android Connected");
socket.on('message', function(message){
console.log("message received");
socket.emit('message', 'message received');
});
});
server.listen(8081)
答案 0 :(得分:2)
在Socket.Java中,您使用localhost:8081/
而不是此地址,而必须使用node.js服务器IP地址(本地IP地址)。要将应用程序与node.js服务器连接,必须将计算机和应用程序运行设备保持在同一网络中。
答案 1 :(得分:1)
另一个答案是正确的。但要注意的另一件事是:如果使用仿真器,则可以使用10.0.2.2引用主机的本地主机。这对于开发非常有用,因为您不必在每次更改网络时都获得笔记本电脑的实际IP地址。
有关更多信息,请参见:https://developer.android.com/studio/run/emulator-networking