[英]fire an event programatically every some seconds using socket.io
My server wants to say "hi" to the clients every interval of time.我的服务器每隔一段时间就想向客户打个招呼。 I have this example of code to demonstrate the event firing according to interval of time.
我有这个代码示例来演示根据时间间隔触发的事件。 But sadly it is not working.
但遗憾的是它不起作用。
server:服务器:
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs');
app.listen(8001);
function handler(req, res) {
fs.readFile(__dirname + '/client1.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client1.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log("runing time");
socket.emit( "clientMessage","hi from server");
socket.on('clientMessage', function () {
socket.emit( "serverMessage","hi from server");
});
socket.on('disconnect', function () {
console.log("disconnecting");
});
});
Client:客户:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost:8001");
socket.on('connection', function(socket) {
// *this line is not reached*
alert("connected")
sendTestMessage()
socket.on("serverMessage", function(d) {
alert("server Message : " + d)
})
socket.on('disconnect', function() {
alert("disconnected")
});
});
function sendTestMessage() {
alert("test")
socket.emit('clientMessage', "Test Message From Client");
setTimeout(sendTestMessage(), 5000)
}
</script>
Please any help why?请任何帮助为什么?
I think the problem may be here: 我认为问题可能在这里:
setTimeout(sendTestMessage(), 5000)
Looks like you are calling the function, but just need to pass a reference instead. 看起来您正在调用该函数,但是只需要传递一个引用即可。
Try: 尝试:
setTimeout(sendTestMessage, 5000);
events on server side and client side should be same.服务器端和客户端的事件应该相同。 you should try this server.js:
你应该试试这个 server.js:
io.on('connection', function (socket) {
console.log("runing time");
setInterval(()=>{
socket.emit("clientMessage","hi from server")
}, 1000)
socket.on('disconnect', function () {
console.log("disconnecting");
});
client.js:客户端.js:
socket.on('connect',()=>{console.log('socket connected')});
socket.on('disconnect',()=>{console.log('socket disconnected')});
socket.on('clientMessage', (msg)=>{
console.log('Message From Server: ', msg)
});
this will emit message from server after every second to client.这将每秒从服务器向客户端发出消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.