[英]Can't receive broadcasted event in client using socket.io
I'm trying to render some data on active.ejs
which has a socket that is listening for the event users
. 我正在尝试在
active.ejs
上呈现一些数据,该数据具有监听事件users
的套接字。 The event users
is emitted as a broadcast by index.js
. 事件
users
通过index.js
广播发送。
I have a console.log("do you go here")
in my socket listener function in active.ejs
. 我在
active.ejs
套接字侦听器函数中有一个console.log("do you go here")
。 However, it never logs "do you go here" in socket.on
so that means somehow the broadcast emitted by index.js
isn't received by active.ejs
. 但是,从来没有记录“你到这里”,在
socket.on
,这样在某种程度上是指所发出的广播index.js
没有收到active.ejs
。 How do I get it to receive it? 我如何获得它呢?
index.js index.js
var io = socket(server);
io.on('connection', function(socket){
count++;
socket.broadcast.emit('users', socket.handshake.query);
});
active.ejs active.ejs
..html boilerplate
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://localhost:4000/socket.io/socket.io.js"></script>
</head>
<body>
<p>
Welcome,
<%= user_info.uri %>
</p>
<div id="active"></div>
<script>
var socket = io.connect('http://localhost:4000/tune-in', {query: <%- JSON.stringify(user_info) %>});
var active = document.getElementById('active');
// Listening for events on socket
socket.on('users', function(data){
console.log('do you go here');
active.innerHTML += "<p><em>" + data.display_name + " is connected" + "</em></p>";
});
</script>
</body>
</html>
Your code socket.broadcast.emit('users', socket.handshake.query);
您的代码
socket.broadcast.emit('users', socket.handshake.query);
does exactly what it should - sends event to all clients except the client that has just connected. 完全按照应有的方式-将事件发送给所有客户端(除了刚刚连接的客户端以外)。
You may want to use io.emit('users', socket.handshake.query)
instead. 您可能要改用
io.emit('users', socket.handshake.query)
。
EDITED: 编辑:
Add the namespace to the server: 将名称空间添加到服务器:
var io = socket(server);
io.of('/tune-in').on('connection', function(socket){
count++;
socket.broadcast.emit('users', socket.handshake.query);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.