【发布时间】:2020-04-28 07:06:06
【问题描述】:
我正在尝试使用 node.js 匹配服务器构建一个简单的颤振聊天应用程序。我已经使用了几个小时,但我无法让应用程序连接到服务器。
这是节点 js 服务器:
var express=require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var allClients = {};
io.on('connection', function (socket) {
io.to(socket.id).emit('userCount', Object.keys(allClients).length);
console.log(socket.id,'joined');
//match making logic
});
var port = 8080;
console.log(port);
server.listen(port);
Flutter 连接代码:
//Find a match for the user
void findMatch() async {
SocketIO socketIO = SocketIOManager().createSocketIO("http://192.168.0.32:8080", "/");
print('Created');
await socketIO.init(); //code execution pauses indefinitely at this line
print('Initialized');
await socketIO.connect();
print('Connected');
socketIO.sendMessage('new user', data);
socketIO.subscribe('match found', (data) async {
UserData peerData = await getUserData(data.peerId);
redirectToPage(context, Chat(peerId: data.peerId, peerData: peerData));
});
}
函数运行时,代码执行在上图行暂停,node js服务器根本没有反应。但是,这会显示在调试控制台上。
D/FlutterSocketIoPlugin: FlutterSocketIoPlugin( 4490): onMethodCall: socketInit - domain: http://192.168.0.32:8080 - with namespace: /
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: TOTAL SOCKETS: ( 4490): 0
D/FlutterSocketIoPlugin: added SocketIO( 4490): http://192.168.0.32:8080/
D/FlutterSocketIoPlugin: SocketIO( 4490): connecting...null
感谢任何帮助。谢谢!
我按照cmets的建议写了一个简单的node js客户端,并成功连接到服务器。
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
编辑:
在 findMatch() 中的套接字函数得到这个之前删除 'await's。
D/FlutterSocketIoPlugin: SocketIO(21368): reconnect_error: [{"cause":{"cause":{"detailMessage":"CLEARTEXT communication to 192.168.0.32 not permitted by network security policy","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"Connection error","stackTrace":[],"suppressedExceptions":[]}]
我在AndroidManifest.xml 中尝试了android:usesCleartextTraffic="true",但它似乎不起作用。将 http 更改为 https 会得到 SSL handshake aborted。也许使用 SSL 证书在远程机器上部署套接字服务器会起作用?将继续挖掘。
【问题讨论】:
-
你能试着用
try...catch换行吗? -
你指的是执行暂停的那一行吗?
-
是的。可能存在未捕获的错误
-
@AugustinR 不,没有发现错误
-
愚蠢的问题。您已经使用不同的客户端测试了您的 API,并且它按预期工作?