{"id":23349994,"url":"https://github.com/omeroot/socketbox","last_synced_at":"2025-04-10T04:51:03.456Z","repository":{"id":57150056,"uuid":"120674844","full_name":"omeroot/socketbox","owner":"omeroot","description":"Write websocket app like as restful api. Inspired by express.","archived":false,"fork":false,"pushed_at":"2018-03-25T22:48:22.000Z","size":123,"stargazers_count":14,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-18T13:58:28.075Z","etag":null,"topics":["es6-modules","javascript","node","nodejs","real-time","socket","websocket"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/omeroot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-02-07T21:36:43.000Z","updated_at":"2018-03-25T22:48:24.000Z","dependencies_parsed_at":"2022-09-03T18:01:19.832Z","dependency_job_id":null,"html_url":"https://github.com/omeroot/socketbox","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omeroot%2Fsocketbox","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omeroot%2Fsocketbox/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omeroot%2Fsocketbox/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/omeroot%2Fsocketbox/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/omeroot","download_url":"https://codeload.github.com/omeroot/socketbox/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248161259,"owners_count":21057552,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["es6-modules","javascript","node","nodejs","real-time","socket","websocket"],"created_at":"2024-12-21T08:14:30.922Z","updated_at":"2025-04-10T04:51:03.436Z","avatar_url":"https://github.com/omeroot.png","language":"JavaScript","readme":"# Socketbox\n\n[![npm version](https://badge.fury.io/js/socketbox.svg)](https://badge.fury.io/js/socketbox)\n[![Build Status](https://travis-ci.org/omeroot/socketbox.svg?branch=master)](https://travis-ci.org/omeroot/socketbox)\n[![Coverage Status](https://coveralls.io/repos/github/omeroot/socketbox/badge.png?branch=master)](https://coveralls.io/github/omeroot/socketbox?branch=master)\n\nSocketbox is real time socket layer framework inspired by express.You can simulate socket messages like as restful request, build router system according to a specific protocol and write middleware to this routers.\n\n```js\nimport Socketbox from 'socketbox';\n// First create your own socket server.\nconst ws = new WebSocket.Server( { port : 8080 } );\n\n// you give socket server instance to socketbox\nconst app = new Socketbox();\n\napp.createServer( ws );\n\n//you create router\nconst router = Socketbox.Router();\n\n//you activate router on this websocket server.\napp.use( '/', router );\n```\n\n## Installation\nThis is a [Node.js](https://nodejs.org/en/) module available through the\n[npm registry](https://www.npmjs.com/package/socketbox).\n\nBefore installing, [download and install Node.js](https://nodejs.org/en/download/).\nNode.js 7 or higher is required.\n\n```bash\n$ npm install socketbox\n```\n\n## Supported socket types\n * Websocket\n\n## Socketbox opts\n```js\nconst app = new Socketbox(opts);\n```\n\nEvents\t \t\t | Description\n-----------------|------------\n`ping`\t    \t | (boolean) ping-pong activate, server send ping message automatic\n`pingTimeout`    | (number) seconds, ping sending timeout\n\n## Basic text message based ping-pong\n##### Your client listen ping text message and reply to this message\n##### !! Strongly recommend set clientTracking to false in websocket opts\n```js\n// client connect to server\nvar wsClient = new WebSocket('ws://localhost:8080', opts);\n\n// example Web browser websocket\nwsClient.onmessage = function(message){ \n  if(message.data === 'ping') {\n    wsClient.send('pong');\n  }\n}\n```\n\n##### If your client dont reply ping message, server know client is down and clear client data on system.\n\n## Socketbox client events\n```js\napp.on(\u003cevents\u003e, (client) =\u003e {\n  console.log(`${client.ip} is connected`);\n});\n```\nEvents\t \t\t | Description\n-----------------|------------\n`connected`    \t | Emitted client connected\n`disconnected`   | Emitted client disconnected\n\n##### Event callback give one parameter, it is client object.\n\n## Client sessions\nYour each client have own session object.You can edit session add and remove directly.\nYou can write data to client session.\n```js\n// example:\n// you validate client and returned user object.You\n// can put user to client session.You can access session in each request \n// session everytime stored until client disconnect\nrouter.register( '/validate/token', ( req, res ) =\u003e {\n  req.session.user = validate(req.body.token); //use session.user on each request\n} );\n```\n\n## Socket message protocol (Client message format)\nYou need to adjust some rules while send message to this socket server from client. Your socket message architecture below;\n\n```js\n{\n  url: 'ws://omer.com/message/write', // hostname and protocol is required current version\n  body: {\n    to: 'x',\n    from: 'y',\n    message: 'hi!'\n  }\n}\n```\nProperty | Description\n---------|------------\n`url`    | ( required ) your defined url on backend server\n`body`   | ( optional ) if you want put data to your message\n\n##### you can put query your url.\n```js\n{\n  url: 'ws://omer.com/message/get?messageId=11993'\n}\n```\n\n## Router \n```js\nrouter.register( '/message/write', ( req, res ) =\u003e {\n  res.send( { statusCode : 200 } );\n} );\n```\nyou can use params while register route path.\n```js\nrouter.register( '/message/write/:userid', ( req, res ) =\u003e {\n  /**\n   * Access to params\n   * req.params.userid\n   * \n   * If you have query in request;\n   * req.query.[\u003cyour query name\u003e]\n   */\n  \n  res.send( { statusCode : 200 } );\n} );\n```\n## Middleware\nYou can add property to request object on middleware.\n```js\nconst mid1 = ( req, res, next ) =\u003e {\n  req.user = {};\n  req.user.username = 'dmomer';\n  next();\n};\n\nrouter.register( '/profile', mid1, ( req, res ) =\u003e {\n  res.send( req.user );\n} );\n```\n\n## Cache\nYou can access socketbox cache but recommend only use the following methods.\nCache class is static class and read-only.Clients is stored in a Map object.\n\n```js\n\n// return everytime same cache class.\nconst cache = Socketbox.Cache();\n```\n**Method: cache.clients()**\n\n - Returns: All clients in a Array.\n\ndon't take parameters.\n\n**Method: cache.filter(key)**\n - key `\u003cstring\u003e | \u003cFunction\u003e` You will be passed to key string or direct working filter function.\n - Returns: All clients in a Array.\n\nFollowing is two differenct parameter example:\n```js\n\n// we have map , which is [['1', {name: 'omer'}], ['2', {name: 'demircan'}]]\n\n// use string key\ncache.filter('1'); // return only values [{name: 'omer'}]\n\n// use own filter function;\n// following function filter objects, which contains name key is 'omer'\ncache.filter((item) =\u003e {\n  // item[1] is value.\n  return item[1].name === 'demircan'\n}) // return [{name: 'demircan'}];\n```\n\n## Channels\nYou can bind clients to channels.You can send message to channel if you want.\n\n#### Join to channel\n**Method: join( cname )**\n\n - cname `\u003cString\u003e` channel name for join\n\n```js\n// if channel is not exist, method create channel.\nclient.join('channel1');\n\n// ex:\n// you can listen join router\nrouter.register('/join?room=223', (req, res) =\u003e {\n  res.join(req.query.room);\n});\n```\n\n#### Send message to channel\n**Method: sendTo(message, cname)**\n\n - message `\u003cString\u003e` message content\n - cname    `\u003cString\u003e` channel name to go\n\n```js\nres.sendTo({message: x}, 'channel1');\n```\n\n#### Leave from channel\n\n## Request\nYou can use some request properties.\n```js\nreq.body; //you can access message body\n\n// if url is /a/b?keyword=omer\n// you can access req.query.keyword (value is omer)\nreq.query; //this is object\n\n// if url is /a/b/:name\n// you can access req.params.name (value is any) \nreq.params; //this is object\n\n// if your url is wss://omer.com/p/a/t/h?query=string#hash\nreq.protocol; //wss:\nreq.host; //omer.com\nreq.hostname; //omer.com\nreq.port; // null\nreq.path; // /p/a/t/h?query=string\nreq.pathname // /p/a/t/h\nreq.href; // wss://omer.com/p/a/t/h?query=string#hash\nreq.query; // 'query=string'\nreq.hash; // #hash\n```\n## Response\n##### Actually response object is client reference.\nYou can put string, json or buffer to message.\n```js\n// you can send Object or raw string\n\nres.send({name: 'omer'});\n\nres.send(new Buffer('omer'));\n```\n\n### Leave from room\n**Method: leave( cname )**\n\n - cname `\u003cString\u003e` channel name for leave\n\nIf client is leaved, return true otherwise return false.\n\n```js\n// res is client reference on all request, you can access to client object using res.\n\nres.leave('room1');\n```\n","funding_links":[],"categories":["\u003ca name=\"JavaScript\"\u003e\u003c/a\u003eJavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fomeroot%2Fsocketbox","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fomeroot%2Fsocketbox","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fomeroot%2Fsocketbox/lists"}