Socket.io setinterval way

I want to create a web page to give the client news about his friends every 1 second using socket.io + node.js.

My codes are:

Customer:

var socket = io.connect('http://localhost:port'); socket.on('connect', function(){ socket.emit('hello', 'Hello guest'); }); socket.on('news_by_server', function(data){ alert(data); }); setInterval(function(){ socket.emit('news', 'I want news :D '); }, 1000); 

server:

  var io = require('socket.io').listen(port); io.sockets.on('connection', function (socket) { socket.on('hello', function(data){ console.log('new client connected'); }); socket.on('news', function(data){ socket.emit('news_by_server', 1); }); }); 

what are the network codes, but my question is INTERVAL, is it good to do news in real time or is there better than that.

+4
source share
2 answers

The client does not need to request news. You can force the server if you want to emit every second - as long as the clients are connected, they will receive updates. If there are no customers, you will see in the logs that nothing is happening.

On server

 setInterval(function(){ socket.emit('news_by_server', 'Cow goes moo'); }, 1000); 

On the client

 socket.on('news_by_server', function(data){ alert(data); }); 
+12
source

This is a pretty standard way to do this. If you have not looked at the sample application page on the .io socket, there is a beibertweet example that does this only with setInterval.

There is also a slightly more advanced example on this blog.

A plus. I found the Ryan Dahls introduction on YouTube, really useful for understanding the basics of node operation.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1395800/


All Articles