I’m exploring socket.io and trying to understand the details of the basic interaction between client and server side. Could someone give me specific commenting and explanation of this basic socket.io program below. I appreciate the help and of course if you give me a good answer I’ll rate you up!
Server Side
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Client Side
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Server side:
The first line starts by binding socket.io on port 80.
Then you write the handler for each connection
io.sockets.on('connection', function (socket) {. In that handlersocketcontains information about the connected client.socket.emitsends a realtime response to the frontend on the channelnewswith the JSON object{ hello: 'world' }.socket.onis listening for all the messages received from that client that are transmitted on the ‘my other event’ channel.Client side:
You start by including the socket.io JavaScript source and connecting the client to the socket.io server on localhost, port 80.
Then the client listens for the messages broadcasted on the channel ‘news’, then logs that message and broadcasts a message back to the server with an object that has the ‘my’ property set to ‘data’.