【发布时间】:2019-03-17 17:04:20
【问题描述】:
我有一个正在运行的 nodejs 服务器,(并且通过浏览器,socket.io 可以正常工作,发送和接收事件)。为了轻松模拟在线连接,我使用 ngrok.io 来隧道我的本地主机。这一切都很好。我想编写一个连接到同一台服务器的小应用程序,但是虽然我的服务器能够接收到 socket.connect() 调用,但它没有接收到任何 .emit() 事件。
(我使用 com.github.nkzawa:socket.io-client:1.0.0 和 socket.io 2.1.1)
这里是相关的服务器代码:
io.on('connection', function (socket) {
console.log('Something has connected to the server: ' + socket.request.session.id);
socket.on('join', function (username) {
if(!username.username){
username = socket.request.session.username;
}else{
username = username.username;}
console.log('[Socket Chat] '+ username +' has connected to chat');
socket.broadcast.emit('sys message', username + " has joined the chat.");
});
});
同样,这段代码运行良好。
应用程序的其他部分可以很好地连接到我的 expressjs 服务器,并且能够连接到数据库以验证登录名和其他内容。所以连接本身没有问题,只是它的 socket.io 部分。
这是相关的应用程序代码(我在手机上运行):
private Socket mSocket;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
try {
//IO.Options opts = new IO.Options();
//opts.port = 3000; tried changing post but didn't help
mSocket = IO.socket(AppConfig.URL_CHAT); // URL_CHAT is correct, and its the same url I use with the browser
}
catch (URISyntaxException e) {
throw new RuntimeException(e);
}
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError); //theres an emitter.listener for these, and they do trigger if my url is incorrect or my internet is down
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.connect();
JSONObject obj = new JSONObject();
try {
obj.put("username", Nickname);
} catch (JSONException e) {
e.printStackTrace();
}
//mSocket.open();
mSocket.emit("join", obj);
我已经尽我所能尝试了这里所有其他答案的所有方法。 当我运行该应用程序时,我的服务器会打印带有会话 ID 的日志“Something has connected: $id”,但不会触发加入事件。事实上,我已经安装了套接字通配符,它也不会接收任何发出的事件,使用代码:
socket.on('*', function (packet){
console.log(packet.data);
});
它确实会从聊天中获取所有其他事件。
我尝试发送不同类型的事件、不同的 json 数据、字符串。
我注意到的一件事是,在应用程序中,socket.connected() 返回为 false,这很奇怪,因为我的服务器也检测到应用程序何时断开连接。
我尝试将 node 上的 socket.io 降级到 2.0.0,但这也不起作用。
两个日志都没有出现错误,所以我无法完全理解这件事有什么问题。 如何让我的服务器捕获 .emit() 事件?
【问题讨论】:
标签: java android node.js express socket.io