【发布时间】:2016-01-27 12:00:40
【问题描述】:
我目前的问题是有两个浏览器(两个用户)。一旦他们两个都连接了,他们可以做一个特定的套接字事件,这是一个朋友请求,但不能同时两个。总是需要刷新一个用户的页面。
举例说明
当用户点击此按钮时
导航栏字形将增加 1
服务器端事件
io.on('connection', function(socket){
// Everytime user is connected, I will do some Database operation to store the socketId, it will look something like this
user.socketId = socket.id; // For simplicity.
console.log(socket.request.user.username); // is using passport-socket.io library
socket.on('friendsRequest', function(data) {
// Got these two datas from input hidden on html by using Jquery
var socketId = data.socketId;
var userId = data.userId;
socket.to(socketId).emit('friendsRequest', socket.request.user);
console.log("Successful" + " from " + socket.request.user.username);
});
奇怪的是,在服务器端它总是显示console.log("Successful" + " from " + socket.request.user.username);,这意味着如果点击两个用户浏览器上的按钮,它将正确显示
"Successful from UserA"
"Successful from UserB"
但问题出在客户端,目标 html 从未改变,它总是浏览器导航栏的字形图标之一会递增
这是客户端的代码
// This event will send the targeted data like socketId and userId back to the server
$(document).on('click', "#addFriend", function(e){
e.preventDefault();
var userId = $('#userId').val();
var socketId = $('#socketId').val();
socket.emit('friendsRequest', {
userId: userId,
socketId: socketId
});
});
// Once the server has done doing his job, this event will listen.
socket.on('friendsRequest', function(data) {
var totalRequests = parseInt($('#totalRequests').html());
console.log(totalRequests);
totalRequests += 1;
$('#totalRequests').html(totalRequests);
$('#friendsRequested').append('<li>' + data + '</li>');
});
主要问题出在客户端socket.on('friendsRequest');
当我触发 friendsRequest 事件时,它仅适用于其中一个浏览器,但不能同时适用于两个浏览器
需要具有 socket.io 专业知识的人向我解释为什么它不能双向工作。至于我的逻辑,它应该可以工作。
html
<input type="hidden" name="socketId" id="socketId" value="ValueOftheSocketId" />
<button type="submit" id="addFriend" class="btn btn-default">Add Friend</button>
【问题讨论】:
标签: node.js express socket.io real-time