我的应用程序,使用socket.io,无法连接到node.js服务器.
服务器node.js
var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(1000);
io.on('connection', function (client) {
client.name = client.remoteAddress + ':' + client.remotePort;
console.log(client.name + ' connected!');
client.on('sensorChanged', function (data) {
console.log("HERE");
console.log(data);
});
});
android应用程序:
SocketIO socket = new SocketIO();
try {
socket.connect("http://localhost:1000/", this);
txtView.setText("connected");
} catch (MalformedURLException e) {
e.printStackTrace();
}
socket.emit("sensorChanged", "argument1");
当我连接到服务器时,服务器不会说“socket.name connected”,并且不会发出事件’sensorChanged’.问题出在哪儿?
最佳答案 建立从Android设备到本地节点服务器的Socket.IO连接
A.确保已通过gradle安装了socket.io-client-java.
B.确保您已为设备启用互联网访问.
<!-- AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
<uses-permission android:name="android.permission.INTERNET" />
<application ...>
...
</application>
</manifest>
C.确保您运行服务器的端口已打开.
> Open Port on Windows 10
> Open Port on Mac OSX 10
D.使用您的计算机网络IP地址连接到本地服务器.
>打开终端.
>输入命令ipconfig.
>查找您的IPv4地址.
您想要连接到http://< IPv4地址>:< port>.
通过http:// localhost:3000连接到localhost将不起作用,因为“localhost”指的是设备本身.
E.测试设备上的连接.
>在服务器GET / status上设置一条简单的路由,返回200.
>导航到设备上的http://< IPv4地址>:< port> / status.
>如果你得到了成功的回应,你应该好好去.
F.您现在应该能够将您的android套接字客户端连接到您的节点套接字服务器.
// Node.js App
let SocketIO = require('socket.io');
let ioServer = SocketIO(server);
console.log('Socket Server waiting for connections');
ioServer.on('connection', function (socket) {
console.log(`Socket Client connected with id=${socket.id}`);
});
–
// Android App
import io.socket.client.Socket;
import io.socket.client.IO;
import io.socket.emitter.Emitter;
import android.util.Log;
public class SocketIO implements Runnable {
@Override
public void run() {
final Socket socket;
try {
socket = IO.socket("http://<IPv4 Address>:<port>");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("TAG", "Socket Connected!");
socket.disconnect();
}
});
} catch(Exception e){
Log.e("Error", e.toString());
}
}
}