SocketIO - Tuong-Nguyen/JavaScript-Structure GitHub Wiki

Install

  • npm install socket.io --save-dev

with koa we use koa-socket:

  • npm install koa-socket --save-dev

Initialization

Server Site

Create an undependency socket server.

  • The socketio need bind on an Httpserver which will specify the ip, port to open socket server:
var app = require('http').createServer(httpHandler);
var io = require('socket.io').listen(app);
var fs = require('fs');

app.listen(7788, ()=>{
    console.log('server is listenig on port 7788');
});

function httpHandler(req,res) {
    res.writeHead(200);
    res.end();
}

The httpHandler function will hanlder the http request to socket server and response data to display in browser.

Create an socket server in koa project:

const koa = require('koa');
const app = module.exports = new koa();
const IO = require('koa-socket');
var io = new IO();
io.attach(app);
app.listen(process.env.PORT || 3000, ()=>{
    "use strict";
   console.log('Listening on port 3000');
});
  • app is the koa app which was declare to hanlder http request and reponse.
  • process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there.
  • Note: in this example the io object is a server socket which will manage all connections.
  • When an connection is established an socket object (client socket) will be generated and it is managed by the io object through an connection map (io.connections).

In client side:

  • To create an websocket using socketio you need import socketio library to you project. Click socket.io.js to download. <script src="/resources/socket.io.js"></script>

Connect

Client side:

  • To connect to socket server var socket = io('http://localhost:3000');
  • If have some problem the socketio will reconnect automatically.

Server side:

  • In server you need create an connection handle. on() function will call when have request or reponse.
  • The on('name', function(){}) function have 2 parameters
  • The 'name' specify which will receive and handle request. It must be same the name of send message(data), with connection and disconnection event you must use 'connection' and 'disconnect' name.
  • The function(){} where you can write your code.
io.on('connection', function (socket) {
    console.log('connected');
    socket.on('disconnect', function () {
        console.log('disconnect');
    })
});

With koa

io.on( 'connection', ( ctx, data ) => {
    console.log('connected');
    ctx.socket.on('disconnect', function () {
        console.log('disconnect');
    })
});
  • When an connection is established an socket object will be generate with an distinct id. We can get it by socket.id (ctx.socket.id).

Send and Receive (client & server)

Send:

  • To send an data or message to server( client) you use the emit('name', data).
  • The 'name' specify an message( data).
socket.emit('hello', 'world');
// with koa
ctx.socket.emit('hello', 'world');
  • in this example the message name is 'hello' and data is 'world'.

Receive:

  • To receive message(data) you use on('name', function(){}) function.
  • The name must be same the send meesage name.
socket.on('hello', function (msg) {
    console.log(msg);
    });
});

Broadcast

  • To send an broadcast message we use socket.broadcast.emit(...)
var time = setInterval(function () {
    socket.broadcast.emit('broadcast', Math.random());
}, 1000);
  • To broadcast to a group(room) we can use: socket.broadcast.to('groupname').emit('broadcast', Math.random());
//join room
ctx.socket.join('roomA');
socket.broadcast.to('roomA').emit('broadcast', Math.random());

Some sending example.

// send to current request socket client
socket.emit('message', "this is a test");
 
// sending to all clients, include sender
io.sockets.emit('message', "this is a test");
 
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
 
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
 
// sending to all clients in 'game' room(channel), include sender
io.sockets.in('game').emit('message', 'cool game');
 
// sending to individual socketid
io.sockets.socket(socketid).emit('message', 'for your eyes only');
⚠️ **GitHub.com Fallback** ⚠️