{"_id":"@awamwang/egg-socket.io","name":"@awamwang/egg-socket.io","dist-tags":{"latest":"4.5.1"},"versions":{"4.5.1":{"name":"@awamwang/egg-socket.io","version":"4.5.1","description":"egg plugin for socket.io","eggPlugin":{"name":"io","dependencies":["session"]},"keywords":["egg","eggPlugin","egg-plugin","socket.io","websocket"],"dependencies":{"@socket.io/redis-adapter":"^7.2.0","debug":"^4.3.4","delegates":"^1.0.0","is-type-of":"^1.2.1","koa-compose":"^4.1.0","redis":"^4.1.0","socket.io":"^4.5.1"},"devDependencies":{"@types/node":"^16.0.0","autod":"^3.1.2","egg":"^2.36.0","egg-bin":"^5.1.1","egg-ci":"^2.1.0","egg-mock":"^4.2.1","egg-redis":"^2.4.0","egg-session-redis":"^2.1.0","eslint":"^8.18.0","eslint-config-egg":"^12.0.0","pedding":"^1.1.0","rimraf":"^3.0.2","semver":"^7.3.7","socket.io-client":"^4.5.1","supertest":"^6.2.3","typescript":"^4.7.4","webstorm-disable-index":"^1.2.0"},"engines":{"node":">=8.0.0"},"scripts":{"test":"npm run lint -- --fix && npm run test-local","test-local":"egg-bin test","cov":"egg-bin cov","lint":"eslint .","ci":"egg-bin pkgfiles --check && npm run lint && npm run cov","autod":"autod"},"ci":{"version":"8, 10","license":true,"services":"redis-server"},"repository":{"type":"git","url":"git+https://github.com/eggjs/egg-socket.io.git"},"bugs":{"url":"https://github.com/eggjs/egg/issues"},"homepage":"https://github.com/eggjs/egg-socket.io#readme","author":{"name":"ngot","email":"zhuanghengfei@gmail.com"},"license":"MIT","publishConfig":{"access":"public"},"types":"./index.d.ts","gitHead":"a5128dae7d477f3ce71cebbc386f1d1e03408cdf","_id":"@awamwang/egg-socket.io@4.5.1","_nodeVersion":"16.15.1","_npmVersion":"8.11.0","dist":{"integrity":"sha512-zX/yZT6UKolhLV0JNqGGBzcXz8bbmj3RIfL47ZBW18yyK3DeD/gAiXVh1/MfeKN+19ktzUa54HETaO/mJXzAvQ==","shasum":"264ddd6722d0a77497a91daaa4a1ddbd5f553822","tarball":"https://registry.npmjs.org/@awamwang/egg-socket.io/-/egg-socket.io-4.5.1.tgz","fileCount":16,"unpackedSize":32193,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCgrp2Gay8cDXjL0zv+xprGDyI8u92i+aLIIhQoLxef4QIgN5aAXCAYUD1eovRxbbh+wBZgLZuJqnTp6/IBn80O7l8="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJiun60ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqpDQ//QtcsXFfFSd4eFO4HNCKCO9QxrcMSa8sN2uF3SlSiLetESEXL\r\nu+oSyZ2usaj7iHZYF4OqWx5QRV+TLWYesh/mOIlT+ovGsUTzsyR6IaN+PkDe\r\nE/fqvPlCQA4Jreu3JsOoRiD9XQALwZB1hp4QJJcR9FgWycoBejQsKHAU7zpJ\r\nuTrh7K6YZMwdzh3ZdKKpJNZzpkkf5UWrHh2TlFgknihXwASWamme6PYiufDz\r\nuiJiPXyDt+2B2y/PJraFZKQQu78iR2NBBEkKPO29Uvrrk8uuGPZ9COiylfXi\r\noWURi+J9q89bicguNrmHgDhxsYyvn7fcW1rY5hi21lrj/B0nmAPC+CFyLl8x\r\nn64C4gLI+cbCje931W0fDJW8nRkq49p7RQODUOBubWv+4nTmcY8T0Dt5lz2M\r\neP4K9LSyrNgCtx7uOghCgIWBKWe4Y0Mh/jPl8ZEZ8sczueRm3UDkA33p8Fs7\r\np5ggXvn4gb+KpoiIzP9SkbhNQdYgYbgXj2X6qirQw/Ec3ch7uAp+XnQzhif6\r\namSj8JzIAKdRlipJZjf2YWArYqMIOHCcaofOkdBhI1E4SAimA80/nmi4U7YC\r\np89+eCvQbCvswXIv4M7CtIyaGlz9th+QASV24v+iVi8ezylNtTlpsRCMWVOV\r\nZnVveHVfrWFP1Z8+SsAjNHyZ7BJ15nHZ/s4=\r\n=RDsr\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"awamwang","email":"wm.keepgoing@gmail.com"},"directories":{},"maintainers":[{"name":"awamwang","email":"wm.keepgoing@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/egg-socket.io_4.5.1_1656389300622_0.39357445961238513"},"_hasShrinkwrap":false}},"time":{"created":"2022-06-28T04:08:20.573Z","4.5.1":"2022-06-28T04:08:20.844Z","modified":"2022-06-28T04:08:21.006Z"},"maintainers":[{"name":"awamwang","email":"wm.keepgoing@gmail.com"}],"description":"egg plugin for socket.io","homepage":"https://github.com/eggjs/egg-socket.io#readme","keywords":["egg","eggPlugin","egg-plugin","socket.io","websocket"],"repository":{"type":"git","url":"git+https://github.com/eggjs/egg-socket.io.git"},"author":{"name":"ngot","email":"zhuanghengfei@gmail.com"},"bugs":{"url":"https://github.com/eggjs/egg/issues"},"license":"MIT","readme":"# egg-socket.io\n\n[![NPM version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![Test coverage][codecov-image]][codecov-url]\n[![David deps][david-image]][david-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![npm download][download-image]][download-url]\n\n[npm-image]: https://img.shields.io/npm/v/egg-socket.io.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/egg-socket.io\n[travis-image]: https://img.shields.io/travis/eggjs/egg-socket.io.svg?style=flat-square\n[travis-url]: https://travis-ci.org/eggjs/egg-socket.io\n[codecov-image]: https://img.shields.io/codecov/c/github/eggjs/egg-socket.io.svg?style=flat-square\n[codecov-url]: https://codecov.io/github/eggjs/egg-socket.io?branch=master\n[david-image]: https://img.shields.io/david/eggjs/egg-socket.io.svg?style=flat-square\n[david-url]: https://david-dm.org/eggjs/egg-socket.io\n[snyk-image]: https://snyk.io/test/npm/egg-socket.io/badge.svg?style=flat-square\n[snyk-url]: https://snyk.io/test/npm/egg-socket.io\n[download-image]: https://img.shields.io/npm/dm/egg-socket.io.svg?style=flat-square\n[download-url]: https://npmjs.org/package/egg-socket.io\n\negg plugin for socket.io\n\n## Install\n\n```bash\n$ npm i egg-socket.io --save\n```\n\n## Requirements\n\n- Node.js >= 8.0\n- Egg.js >= 2.0\n\n## Configuration\n\nChange `${app_root}/config/plugin.js` to enable Socket.IO plugin:\n\n```js\n// {app_root}/config/plugin.js\nexports.io = {\n  enable: true,\n  package: 'egg-socket.io',\n};\n```\n\nConfigure Socket.IO in `${app_root}/config/config.default.js`:\n\n```js\nexports.io = {\n  init: { }, // passed to engine.io\n  namespace: {\n    '/': {\n      connectionMiddleware: [],\n      packetMiddleware: [],\n    },\n  },\n  redis: {\n    host: '127.0.0.1',\n    port: 6379\n  }\n};\n```\n\n#### uws\n\n**Egg's socket is using `ws`, [uws](https://www.npmjs.com/package/uws) is deprecated due to [some reasons](https://github.com/socketio/socket.io/issues/3319).**\n\nIf you insist using this, please config like this following:\n\n```js\nexports.io = {\n  init: { wsEngine: 'uws' },\n};\n```\n\n- For more options in `init` : [engine.io](https://github.com/socketio/engine.io/blob/master/README.md#methods-1).\n- For more configs of `Egg Socket` in default : [config.default.js](config/config.default.js).\n\n### generateId\n\n```\nnot supported\n```\n\n**Note:** This function is left on purpose to override and generate a unique ID according to your own rule:\n\n```js\nexports.io = {\n  generateId: (request) => {\n        // Something like UUID.\n        return 'This should be a random unique ID';\n    }\n};\n```\n\n## Deployment\n\n### Node Conf\n\nBecause of socket.io's design, the multi process socket.io server must work at `sticky` mode.\n\nSo, you must start cluster server with `sticky` set to true, otherwise it will cause handshake exception.\n\n```bash\n$ # modify your package.json - npm scripts\n$ egg-bin dev --sticky\n$ egg-scripts start --sticky\n```\n\nwhich will start egg cluster with:\n\n```js\nstartCluster({\n  sticky: true,\n  ...\n});\n```\n\n\n### Nginx Conf\n\nif you use a nginx proxy server:\n\n```\nlocation / {\n    proxy_set_header Upgrade $http_upgrade;\n    proxy_set_header Connection \"upgrade\";\n    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n    proxy_set_header Host $host;\n    proxy_pass   http://127.0.0.1:{ your node server port };\n}\n```\n\n## Usage\n\n### Directory Structure\n\n```\napp\n├── io\n│   ├── controller\n│   │   └── chat.js\n│   └── middleware\n│       ├── auth.js\n│       ├── filter.js\n├── router.js\nconfig\n ├── config.default.js\n └── plugin.js\n```\n\n### Middleware\n\nmiddleware are functions which every connection or packet will be processed by.\n\n#### Connection Middleware\n\n- Write your connection middleware\n`app/io/middleware/auth.js`\n```js\nmodule.exports = app => {\n    return async (ctx, next) => {\n        ctx.socket.emit('res', 'connected!');\n        await next();\n        // execute when disconnect.\n        console.log('disconnection!');\n    };\n};\n```\n- then config this middleware to make it works.\n\n`config/config.default.js`\n```js\nexports.io = {\n  namespace: {\n    '/': {\n      connectionMiddleware: ['auth'],\n    },\n  },\n};\n```\n\npay attention to the namespace, the config will only work for a specific namespace.\n\n#### Packet Middleware\n\n- Write your packet middleware\n`app/io/middleware/filter.js`\n```js\nmodule.exports = app => {\n    return async (ctx, next) => {\n        ctx.socket.emit('res', 'packet received!');\n        console.log('packet:', this.packet);\n        await next();\n    };\n};\n```\n- then config this middleware to make it works.\n\n`config/config.default.js`\n```js\nexports.io = {\n  namespace: {\n    '/': {\n      packetMiddleware: ['filter'],\n    },\n  },\n};\n```\n\npay attention to the namespace, the config will only work for a specific namespace.\n\n### Controller\n\ncontroller is designed to handle the `emit` event from the client.\n\nexample:\n\n`app/io/controller/chat.js`\n```js\nmodule.exports = app => {\n  class Controller extends app.Controller {\n    async ping() {\n      const message = this.ctx.args[0];\n      await this.ctx.socket.emit('res', `Hi! I've got your message: ${message}`);\n    }\n  }\n  return Controller\n};\n\n // or async functions\nexports.ping = async function() {\n  const message = this.args[0];\n  await this.socket.emit('res', `Hi! I've got your message: ${message}`);\n};\n```\n\nnext, config the router at `app/router.js`\n```js\nmodule.exports = app => {\n  // or app.io.of('/')\n  app.io.route('chat', app.io.controller.chat.ping);\n};\n```\n\n### Router\n\nA router is mainly responsible for distributing different events corresponding to a controller on a specific socket connection.\n\nIt should be configured at `app/router.js` refer to the last chapter.\n\nBesides that, there are several system Event:\n\n- `disconnecting` doing the disconnect\n- `disconnect` connection has disconnected\n- `error` Error occured\n\nExample：\n\n`app/router.js`\n```js\napp.io.route('disconnect', app.io.controller.chat.disconnect);\n```\n\n`app/io/controller/chat.js`\n```js\nmodule.exports = (app) => {\n  class Controller extends app.Controller {\n    async disconnect() {\n      const message = this.ctx.args[0];\n      console.log(message);\n    }\n  }\n  return Controller\n};\n```\n\n### Session\n\nThe session is supported by `egg-socket.io`. It's behaviour just like the normal HTTP session.\n\nSession 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.\n\nThe feature is powered by [egg-session](https://github.com/eggjs/egg-session), make sure it has been enabled.\n\n## Cluster\n\nIf 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.\n\nIt's very easy to implement sharing source and event dispatch with [socket.io-redis](https://github.com/socketio/socket.io-redis) built in.\n\nconfig at `config/config.${env}.js` ：\n\n```js\nexports.io = {\n  redis: {\n    host: { redis server host },\n    port: { redis server prot },\n    auth_pass: { redis server password },\n    db: 0,\n  }\n};\n```\n\nApplication will try to connect the redis server when booting.\n\n## Questions & Suggestions\n\n### 已知问题\n\n- client.on('error'|'connect_error')捕获不到connectionMiddleware和packetMiddleware抛出的异常\n- redis不自动连接（是否按需连接，待验证）\n\nPlease open an issue [here](https://github.com/eggjs/egg/issues).\n\n## License\n\n[MIT](LICENSE)\n","readmeFilename":"README.md"}