[英]Real time notification with socket.io, react.js and node.js
I'm developing a gaming application with react.js
, node.js
, express.js
and sequelize
. 我正在使用
react.js
, node.js
, express.js
和sequelize
开发游戏应用程序。
The application is simple, one player challenge another player (Active players) and play a game after challenge is accepted. 该应用程序很简单,一个玩家挑战另一个玩家(活跃玩家),并在接受挑战后玩游戏。
I'm trying to create a notification system with socket.io
, but the socket.emit()
isn't working under the socket.on()
at node.js
. 我试图创建一个通知系统
socket.io
,但socket.emit()
是不是下工作socket.on()
在node.js
。 I don't know what's going on? 我不知道怎么回事?
Here my code: 这是我的代码:
React
反应
Sending this challenge request on challenge button click: 通过点击“挑战”按钮发送挑战请求:
socket.emit('challenge request', {
player1_Name : localStorage.getItem('user-name'),
player2 : response.data.data.player2_id,
game : response.data.data.gameId,
gameOption : response.data.data.gameOptionId,
challengeStatus : response.data.data.challengeStatus
});
and trying to receive this notification from the node.js
: 并尝试从
node.js
接收此通知:
socket.on("challenge-notify", function(data) {
console.log("challenge Notify", data);
helper(data.player1_Name,data.player2,data.game,data.gameOption);
});
Node
节点
Here socket.emit('challenge-notify')
function is not working under the socket.on('challenge request')
method: 这里的
socket.emit('challenge-notify')
函数在socket.on('challenge request')
方法下socket.on('challenge request')
:
io.on('connection', function (socket) {
socket.on('challenge request', function (challengeReq) {
socket.emit('challenge-notify', {
player1_Name : challengeReq.player1_Name,
player2 : challengeReq.player2,
game : challengeReq.game,
gameOption : challengeReq.gameOption,
challengeStatus : challengeReq.challengeStatus
});
});
});
If I put socket.emit('challenge-notify')
method outside my socket.on('challenge request')
method then I'm getting the result at console when my react component load. 如果我将
socket.emit('challenge-notify')
方法放在我的socket.on('challenge request')
方法之外,那么当我的socket.on('challenge request')
组件加载时,我会在控制台上得到结果。
But I want this result whenever challenge button clicked. 但是,只要单击挑战按钮,我都希望得到这个结果。 How can I achieve this?
我该如何实现?
Yeah, Finally I found the solution.. 是的,终于找到了解决方案。
I want to use socket.emit
inside the socket.on
to do this I used io.sockets.emit
method and it works fine. 我想用
socket.emit
里面socket.on
要做到这一点我用io.sockets.emit
方法,它工作正常。
socket.on('challenge request', function (challengeReq) {
io.sockets.emit('challenge-notify', {
player1_Name : challengeReq.player1_Name,
player1: challengeReq.player1,
player2 : challengeReq.player2,
game : challengeReq.game,
gameOption : challengeReq.gameOption,
challengeStatus : challengeReq.challengeStatus
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.