{"id":15015812,"url":"https://github.com/thoov/ember-websockets","last_synced_at":"2025-05-16T14:04:31.632Z","repository":{"id":21652036,"uuid":"24972805","full_name":"thoov/ember-websockets","owner":"thoov","description":"Ember.js websockets and socket.io addon","archived":false,"fork":false,"pushed_at":"2023-03-04T15:15:08.000Z","size":3214,"stargazers_count":339,"open_issues_count":19,"forks_count":58,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-05-13T19:24:48.725Z","etag":null,"topics":["ember","ember-addon","javascript","socket-io","websockets"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thoov.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-10-09T03:52:19.000Z","updated_at":"2025-01-24T05:47:38.000Z","dependencies_parsed_at":"2024-06-18T14:06:48.329Z","dependency_job_id":null,"html_url":"https://github.com/thoov/ember-websockets","commit_stats":null,"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoov%2Fember-websockets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoov%2Fember-websockets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoov%2Fember-websockets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thoov%2Fember-websockets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thoov","download_url":"https://codeload.github.com/thoov/ember-websockets/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254544146,"owners_count":22088807,"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":["ember","ember-addon","javascript","socket-io","websockets"],"created_at":"2024-09-24T19:47:59.126Z","updated_at":"2025-05-16T14:04:31.598Z","avatar_url":"https://github.com/thoov.png","language":"JavaScript","readme":"ember-websockets\n==============================================================================\n\n[![GitHub Actions CI][github-actions-badge]][github-actions-ci-url]\n\n[github-actions-badge]: https://github.com/thoov/ember-websockets/workflows/CI/badge.svg\n[github-actions-ci-url]: https://github.com/thoov/ember-websockets/actions?query=workflow%3ACI\n\nCompatibility\n------------------------------------------------------------------------------\n\n* Ember.js v3.24 or above\n* Ember CLI v3.24 or above\n* Node.js v12 or above\n\n\nInstallation\n------------------------------------------------------------------------------\n\n```\nember install ember-websockets\n```\n\n\nUsage\n------------------------------------------------------------------------------\n\n## Simple example of using it in your app\n\n```javascript\nimport Controller from '@ember/controller';\nimport { inject as service } from '@ember/service';\nimport { action } from '@ember/object';\n\nexport default class MyController extends Controller {\n\n  /*\n   * 1. Inject the websockets service\n   */\n  @service('websockets') websockets;\n  socketRef = null,\n\n  constructor() {\n    super(...arguments);\n\n    /*\n      2. The next step you need to do is to create your actual websocket. Calling socketFor\n      will retrieve a cached websocket if one exists or in this case it\n      will create a new one for us.\n    */\n    const socket = this.websockets.socketFor('ws://localhost:7000/');\n\n    /*\n      3. The next step is to define your event handlers. All event handlers\n      are added via the `on` method and take 3 arguments: event name, callback\n      function, and the context in which to invoke the callback. All 3 arguments\n      are required.\n    */\n    socket.on('open', this.myOpenHandler, this);\n    socket.on('message', this.myMessageHandler, this);\n    socket.on('close', this.myCloseHandler, this);\n\n    this.set('socketRef', socket);\n  }\n\n  myOpenHandler(event) {\n    console.log(`On open event has been called: ${event}`);\n  }\n\n  myMessageHandler(event) {\n    console.log(`Message: ${event.data}`);\n  }\n\n  myCloseHandler(event) {\n    console.log(`On close event has been called: ${event}`);\n  }\n\n  @action\n  sendButtonPressed() {\n    this.socketRef.send('Hello Websocket World');\n  }\n}\n```\n\n## Sending messages to the server\n\n```javascript\nconst socket = this.socketService.socketFor('ws://localhost:7000/');\nsocket.send({username: 'foo', didSomeAction: 'pressedAButton'}, true);\n\n// the above line is the same as this:\nsocket.send(JSON.stringify({username: 'foo', didSomeAction: 'pressedAButton'}));\n```\n\nThe send method takes 2 arguments. A message which is passed into the native websockets send method and an\noptional stringify boolean. This boolean, if set to true, will do a JSON.stringify to the message\nbefore passing it to the websocket send method. If you are sending strings it is recommended to pass true.\n\n## Reconnecting\n\n```javascript\nimport Controller from '@ember/controller';\nimport { inject as service } from '@ember/service';\nimport { later } from '@ember/runloop';\n\nexport default class MyController extends Controller {\n  @service('websockets') socketService;\n\n  constructor() {\n    super(...arguments);\n\n    const socket = this.socketService.socketFor('ws://localhost:7000/');\n    socket.on('close', this.myOnClose, this);\n  }\n\n  myOnClose() {\n    const socket = this.socketService.socketFor('ws://localhost:7000/');\n    later(this, () =\u003e {\n      /*\n        This will remove the old socket and try and connect to a new one on the same url.\n        NOTE: that this does not need to be in a Ember.run.later this is just an example on\n        how to reconnect every second.\n      */\n      socket.reconnect();\n    }, 1000);\n  }\n}\n```\n\n## Closing the connection\n\n```javascript\nimport Component from '@ember/component';\nimport { inject as service } from '@ember/service';\n\nexport default class MyComponent extends Component {\n  @service('websockets') socketService;\n\n  /*\n    To close a websocket connection simply call the closeSocketFor method. NOTE: it is good\n    practice to close any connections after you are no longer in need of it. A good\n    place for this clean up is in the willDestroyElement method of the object.\n  */\n  willDestroyElement() {\n    this.socketService.closeSocketFor('ws://localhost:7000/');\n  }\n}\n```\n\n## Multiple Websockets\n\n```javascript\nimport Component from '@ember/component';\nimport { inject as service } from '@ember/service';\n\nexport default class MyComponent extends Component {\n  @service('websockets') socketService;\n\n  didInsertElement() {\n    const socketOne = this.socketService.socketFor('ws://localhost:7000/');\n    const socketTwo = this.socketService.socketFor('ws://localhost:7001/');\n\n    socketOne.on('open', this.myOpenFirst, this);\n    socketTwo.on('open', this.myOpenSeconds, this);\n  }\n\n  myOpenFirst(event) {\n    console.log('Hello from socket one');\n  }\n\n  myOpenSecond(event) {\n    console.log('Hello from socket two');\n  }\n\n  willDestroyElement() {\n    const socketOne = this.socketService.socketFor('ws://localhost:7000/');\n    const socketTwo = this.socketService.socketFor('ws://localhost:7001/');\n    socketOne.off('open', this.myOpenFirst);\n    socketTwo.off('open', this.myOpenSecond);\n  }\n}\n```\n\n## Multiple Event Handlers\n\n```javascript\nimport Component from '@ember/component';\nimport { inject as service } from '@ember/service';\n\nexport default class MyComponent extends Component {\n  socketService: service('websockets'),\n\n  didInsertElement() {\n    const socket = this.socketService.socketFor('ws://localhost:7000/');\n\n    socket.on('open', this.myOpenFirst, this);\n    socket.on('open', this.myOpenSecond, this);\n  }\n\n  myOpenFirst() {\n    console.log('This will be called');\n  }\n\n  myOpenSecond() {\n    console.log('This will also be called');\n  }\n\n  willDestroyElement() {\n    const socket = this.socketService.socketFor('ws://localhost:7000/');\n    socket.off('open', this.myOpenFirst);\n    socket.off('open', this.myOpenSecond);\n  }\n}\n```\n\n## Socket.IO Support\n\nFirst set socketIO to be true in your `config/environment.js` file:\n\n```js\nvar ENV = {\n  'ember-websockets': {\n    socketIO: true\n  }\n};\n```\n\n```javascript\nimport Component from '@ember/component';\nimport { inject as service } from '@ember/service';\n\nexport default class MyComponent extends Component {\n\n  /*\n    1. Inject the socketio service\n  */\n  @service('socket-io') socketIOService;\n\n  /*\n    Important note: The namespace is an implementation detail of the Socket.IO protocol...\n    http://socket.io/docs/rooms-and-namespaces/#custom-namespaces\n  */\n  namespace = 'myCustomNamespace',\n\n  didInsertElement() {\n    /*\n      2. The next step you need to do is to create your actual socketIO.\n    */\n    const socket = this.socketIOService.socketFor(`http://localhost:7000/${this.namespace}`);\n\n    /*\n    * 3. Define any event handlers\n    */\n    socket.on('connect', this.onConnect, this);\n    socket.on('message', this.onMessage, this);\n\n    /*\n      4. It is also possible to set event handlers on specific events\n    */\n    socket.on('myCustomEvent', () =\u003e { socket.emit('anotherCustomEvent', 'some data'); });\n  }\n\n  onConnect() {\n    const socket = this.socketIOService.socketFor(`http://localhost:7000/${this.namespace}`);\n\n    /*\n      There are 2 ways to send messages to the server: send and emit\n    */\n    socket.send('Hello World');\n    socket.emit('Hello server');\n  }\n\n  onMessage(data) {\n    // This is executed within the ember run loop\n  }\n\n  myCustomEvent(data) {\n    const socket = this.socketIOService.socketFor(`http://localhost:7000/${this.namespace}`);\n    socket.emit('anotherCustomEvent', 'some data');\n  }\n\n  willDestroyElement() {\n    const socket = this.socketIOService.socketFor(`http://localhost:7000/${this.namespace}`);\n    socket.off('connect', this.onConnect);\n    socket.off('message', this.onMessage);\n    socket.off('myCustomEvent', this.myCustomEvent);\n  }\n}\n```\n\n**Please visit**: [socket.io docs](https://github.com/thoov/ember-websockets/blob/master/docs/socket-io.md) for more details on ember-websocket + socket.io\n\n## Detailed explanations of the APIs\n\n### SocketFor\n\nExample:\n\n```javascript\nconst socket = this.socketService.socketFor('ws://localhost:7000/', ['myOptionalProtocol']);\n```\n\nsocketFor takes two arguments: **a url**, **a protocol array** (optional), and returns a socket instance from its cache or a new websocket connection if one was not found.\n\nTo use a custom namespace, append the namespace to the end of the url.\n\n```javascript\nconst socket = this.socketService.socketFor(`ws://localhost:7000/${namespace}`);\n```\n\n### On\n\nExample:\n\n```javascript\nconst socket = this.socketService.socketFor('ws://localhost:7000/');\n\nsocket.on('open', this.myOtherOpenFunction);\n```\n\non takes 3 arguments: **event type**, **callback function**, and **context**. Event type can be one of the following: 'open', 'message', 'close', and 'error'. Callback function will be invoked when one of the event types occurs.\n\n### Off\n\nExample:\n\n```javascript\nconst socket = this.socketService.socketFor('ws://localhost:7000/');\n\nlet openFunctionReference = this.myOpenFunction.bind(this);\n\nsocket.on('open', openFunctionReference);\nsocket.off('open', openFunctionReference);\n```\n\noff takes 2 arguments: **event type**, **callback function**. Event type can be one of the following: 'open', 'message', 'close', and 'error'. The callback will be removed from the event pool and will no longer be invoked.\n\n### CloseSocketFor\n\nExample:\n\n```javascript\nthis.socketService.closeSocketFor('ws://localhost:7000/');\n```\n\ncloseSocketFor takes a single argument, **a url**, and closes the websocket connection. It will also remove it from the cache. In normal cases you would not have to call this method.\n\n### Reconnect\n\nExample:\n\n```javascript\nsocket.on('close', event =\u003e {\n  socket.reconnect();\n});\n```\n\nreconnect takes no arguments. It will attempt to create a new websocket connect using the previous url. If the connect is not successful the `close` event will be triggered.\n\n## Live Example\n\n* `git clone git@github.com:thoov/ember-websockets.git`\n* `cd ember-websockets`\n* `yarn`\n* `ember s`\n* Then visit http://localhost:4200/sockets/example to view a very simple example.\n\nThe source code for the live example lives in `ember-websockets/tests/dummy`\n\n## Running tests\n\n* `git clone git@github.com:thoov/ember-websockets.git`\n* `cd ember-websockets`\n* `yarn`\n* `ember t`\n* or `ember s` then visit http://localhost:4200/tests to view the tests.\n\n**NOTE**: To get the test to run in PhantomJS I created a mocking library found here: [mocking library](https://github.com/thoov/mock-socket) Note that it is still a work in progress.\n\n## Feedback or issues\n\nIf you have any feedback, encounter any bugs, or just have a question, please feel free to create a [github issue](https://github.com/thoov/ember-websockets/issues/new) or send me a tweet at [@thoov](https://twitter.com/thoov).\n\n## FAQ\n\n### Recommended backend library/framework\n* [ws](https://github.com/einaros/ws)\n* [socket.io](http://socket.io)\n\nContributing\n------------------------------------------------------------------------------\n\nSee the [Contributing](CONTRIBUTING.md) guide for details.\n\n\nLicense\n------------------------------------------------------------------------------\n\nThis project is licensed under the [MIT License](LICENSE.md).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthoov%2Fember-websockets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthoov%2Fember-websockets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthoov%2Fember-websockets/lists"}