Skip to content

2.4 Sockets

leonardo Rico edited this page Nov 20, 2017 · 1 revision

Socket

Create a file with .js extension in the /src/api/sockets folder

src/api/sockets/hello.js

export let socket = null;
export let io = null;

// Constructor
export default (_socket, _io) => {
    socket = _socket;
    io = _io;
    on();
}

// Here should be all events 'on'
export function on() {
  // Listen 'example'
    socket.on('example', function (data) {
  // Emit to cool
      emit('cool', data);
    });
}

// Emit events
export function emit(event, data) {
    io.emit(event, data);
}

Controller + Socket

src/api/controllers/hello.js

import { result } from 'express-easy-helper';
import { emit } from '../sockets/hello';

export function test(req, res) {

  emit('hello','world');
  return result(res, 'Socket emitted!');

}

More info https://socket.io/docs

Clone this wiki locally