All Projects → eggjs → Egg Socket.io

eggjs / Egg Socket.io

Licence: mit
socket.io plugin for eggjs.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Egg Socket.io

Light Push
轻量级推送服务和实时在线监控平台,同时用于开发即时通信系统,基于node的socket.io,支持web、android、ios客户端,支持移动端离线推送,可进行分布式部署
Stars: ✭ 128 (-38.76%)
Mutual labels:  websocket, socket-io
Python Engineio
Python Engine.IO server and client
Stars: ✭ 167 (-20.1%)
Mutual labels:  websocket, socket-io
Egg View Vue
vue view plugin for egg
Stars: ✭ 136 (-34.93%)
Mutual labels:  egg, egg-plugin
Egg Router Plus
The missing router feature for eggjs
Stars: ✭ 117 (-44.02%)
Mutual labels:  egg, egg-plugin
Cool Admin Api
cool-admin-api 是基于egg.js、typeorm、jwt等封装的api开发脚手架、快速开发api接口
Stars: ✭ 188 (-10.05%)
Mutual labels:  egg, egg-plugin
Node Multiple Rooms Chat
node socket.io multiple room chat demo
Stars: ✭ 118 (-43.54%)
Mutual labels:  websocket, socket-io
Itunes Remote
Remotely control iTunes on Mac without Internet 🎶📱
Stars: ✭ 160 (-23.44%)
Mutual labels:  websocket, socket-io
Egg Schedule
Schedule plugin for egg
Stars: ✭ 76 (-63.64%)
Mutual labels:  egg, egg-plugin
Wechat
聊天系统、Vue.js、React.js、node.js、MongoDB、websocket、socket.io、前后端分离、毕业设计。
Stars: ✭ 188 (-10.05%)
Mutual labels:  websocket, socket-io
Egg Oauth2 Server
🌟 OAuth2 server plugin for egg.js based on node-oauth2-server
Stars: ✭ 174 (-16.75%)
Mutual labels:  egg, egg-plugin
Egg Passport
passport plugin for egg
Stars: ✭ 98 (-53.11%)
Mutual labels:  egg, egg-plugin
Egg Security
Security plugin for egg, force performance too.
Stars: ✭ 204 (-2.39%)
Mutual labels:  egg, egg-plugin
Chat Engine
Object oriented event emitter based framework for building chat applications in Javascript.
Stars: ✭ 87 (-58.37%)
Mutual labels:  websocket, socket-io
Tap Tap Adventure
Tap Tap Adventure is a massively online 2D MMORPG set in the medieval times with twists.
Stars: ✭ 123 (-41.15%)
Mutual labels:  websocket, socket-io
Laverna
Laverna is a JavaScript note taking application with Markdown editor and encryption support. Consider it like open source alternative to Evernote.
Stars: ✭ 8,770 (+4096.17%)
Mutual labels:  websocket, socket-io
Egg Multipart
multipart plugin for egg
Stars: ✭ 145 (-30.62%)
Mutual labels:  egg, egg-plugin
Tyloo Chat
vue + nestjs IM即时通讯聊天室(仿wechat)
Stars: ✭ 54 (-74.16%)
Mutual labels:  websocket, socket-io
Socketio Examples
A few examples that demonstrate the features of the Python Socket.IO server
Stars: ✭ 72 (-65.55%)
Mutual labels:  websocket, socket-io
Flutter socket io
Socket IO supprt for flutter. Looking for contributors Swift and Java.
Stars: ✭ 170 (-18.66%)
Mutual labels:  websocket, socket-io
Cuckoo
🎥 Cuckoo - A free anonymous video-calling web application built with WebRTC and React that provides peer-to-peer video and audio communication in a web browser with no plugins or extensions required.
Stars: ✭ 195 (-6.7%)
Mutual labels:  websocket, socket-io

egg-socket.io

NPM version build status Test coverage David deps Known Vulnerabilities npm download

egg plugin for socket.io

Install

$ npm i egg-socket.io --save

Requirements

  • Node.js >= 8.0
  • Egg.js >= 2.0

Configuration

Change ${app_root}/config/plugin.js to enable Socket.IO plugin:

// {app_root}/config/plugin.js
exports.io = {
  enable: true,
  package: 'egg-socket.io',
};

Configure Socket.IO in ${app_root}/config/config.default.js:

exports.io = {
  init: { }, // passed to engine.io
  namespace: {
    '/': {
      connectionMiddleware: [],
      packetMiddleware: [],
    },
  },
  redis: {
    host: '127.0.0.1',
    port: 6379
  }
};

uws

Egg's socket is using ws, uws is deprecated due to some reasons.

If you insist using this, please config like this following:

exports.io = {
  init: { wsEngine: 'uws' },
};

generateId

Note: This function is left on purpose to override and generate a unique ID according to your own rule:

exports.io = {
  generateId: (request) => {
        // Something like UUID.
        return 'This should be a random unique ID';
    }
};

Deployment

Node Conf

Because of socket.io's design, the multi process socket.io server must work at sticky mode.

So, you must start cluster server with sticky set to true, otherwise it will cause handshake exception.

$ # modify your package.json - npm scripts
$ egg-bin dev --sticky
$ egg-scripts start --sticky

which will start egg cluster with:

startCluster({
  sticky: true,
  ...
});

Nginx Conf

if you use a nginx proxy server:

location / {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass   http://127.0.0.1:{ your node server port };
}

Usage

Directory Structure

app
├── io
│   ├── controller
│   │   └── chat.js
│   └── middleware
│       ├── auth.js
│       ├── filter.js
├── router.js
config
 ├── config.default.js
 └── plugin.js

Middleware

middleware are functions which every connection or packet will be processed by.

Connection Middleware

  • Write your connection middleware app/io/middleware/auth.js
module.exports = app => {
    return async (ctx, next) => {
        ctx.socket.emit('res', 'connected!');
        await next();
        // execute when disconnect.
        console.log('disconnection!');
    };
};
  • then config this middleware to make it works.

config/config.default.js

exports.io = {
  namespace: {
    '/': {
      connectionMiddleware: ['auth'],
    },
  },
};

pay attention to the namespace, the config will only work for a specific namespace.

Packet Middleware

  • Write your packet middleware app/io/middleware/filter.js
module.exports = app => {
    return async (ctx, next) => {
        ctx.socket.emit('res', 'packet received!');
        console.log('packet:', this.packet);
        await next();
    };
};
  • then config this middleware to make it works.

config/config.default.js

exports.io = {
  namespace: {
    '/': {
      packetMiddleware: ['filter'],
    },
  },
};

pay attention to the namespace, the config will only work for a specific namespace.

Controller

controller is designed to handle the emit event from the client.

example:

app/io/controller/chat.js

module.exports = app => {
  class Controller extends app.Controller {
    async ping() {
      const message = this.ctx.args[0];
      await this.ctx.socket.emit('res', `Hi! I've got your message: ${message}`);
    }
  }
  return Controller
};

 // or async functions
exports.ping = async function() {
  const message = this.args[0];
  await this.socket.emit('res', `Hi! I've got your message: ${message}`);
};

next, config the router at app/router.js

module.exports = app => {
  // or app.io.of('/')
  app.io.route('chat', app.io.controller.chat.ping);
};

Router

A router is mainly responsible for distributing different events corresponding to a controller on a specific socket connection.

It should be configured at app/router.js refer to the last chapter.

Besides that, there are several system Event:

  • disconnecting doing the disconnect
  • disconnect connection has disconnected
  • error Error occured

Example:

app/router.js

app.io.route('disconnect', app.io.controller.chat.disconnect);

app/io/controller/chat.js

module.exports = (app) => {
  class Controller extends app.Controller {
    async disconnect() {
      const message = this.ctx.args[0];
      console.log(message);
    }
  }
  return Controller
};

Session

The session is supported by egg-socket.io. It's behaviour just like the normal HTTP session.

Session creates or check just happens at the handshake period. Session can be accessed by ctx.session in packetMiddleware and controller, but it's only created at the handshake period.

The feature is powered by egg-session, make sure it has been enabled.

Cluster

If your Socket.IO service is powered by mutil server, you must think about cluster solution. It can't work without cluster like broadcast, rooms and so on.

It's very easy to implement sharing source and event dispatch with socket.io-redis built in.

config at config/config.${env}.js

exports.io = {
  redis: {
    host: { redis server host },
    port: { redis server prot },
    auth_pass: { redis server password },
    db: 0,
  }
};

Application will try to connect the redis server when booting.

Questions & Suggestions

Please open an issue here.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].