Skip to content

Instantly share code, notes, and snippets.

@n3tr
Forked from woraperth/webSocket.js
Last active June 21, 2018 02:25
Show Gist options
  • Save n3tr/b5fab439f61d8a110026f1103bb0439a to your computer and use it in GitHub Desktop.
Save n3tr/b5fab439f61d8a110026f1103bb0439a to your computer and use it in GitHub Desktop.
JavaScript Singleton to connect to WebSocket (originally for React project)
// App.js
import { getWebSocket } from './webSocket'
let ws = getWebSocket()
ws.send(...)
ws.onmessage = ev => { console.log(ev.data) }
// SomeComponent.js
import { getWebSocket } from './../webSocket'
let ws = getWebSocket()
// Thank you Ranatchai Chernbamrung for sample socketIO singleton pattern
// This code is originally for my React project, but should work with any ES6 project that support `import` statement
// How it works
// 1. Create webSocket.js to establish the connection and retrieve the connection
// 2. In main file, import webSocket.js to establish the connection
// 3. In other component files, import webSocket.js to retrieve the connection
// webSocket.js
let client
export const getWebSocket = () => {
if (client) {
return client;
}
client = new WebSocket('ws://localhost:4237')
return client
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment