socket.io

19/10/2019

Client in html


client in nodejs

var io = require('socket.io-client');

var socket = io('http://localhost:3000', { transports: ['websocket'], upgrade: false });
socket.on('connect', function() {
    console.log('connected')
});

Server standalone

var io = require('socket.io')();
io.on('connection', function(socket){
  console.log('Socket connection established');
  socket.on('disconnect', function () {
      console.log('Socket disconnected');
  });
});
io.listen(3000);

console.log('Listening to port 3000');

Server with express

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);
// WARNING: app.listen(80) will NOT work here!

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
  socket.on('disconnect', function () {
      console.log('Socket disconnected');
  });
});