Skip to content

Instantly share code, notes, and snippets.

@MossP
Forked from woraperth/webSocket.js
Created May 14, 2019 00:28
Show Gist options
  • Select an option

  • Save MossP/69e547866768ea03089c809071e70bcd to your computer and use it in GitHub Desktop.

Select an option

Save MossP/69e547866768ea03089c809071e70bcd to your computer and use it in GitHub Desktop.
JavaScript Singleton to connect to WebSocket (originally for React project)
// 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 initws = (mesg) => {
client = new WebSocket('ws://localhost:4237')
return client
}
export const getws = () => {
return client
}
// App.js
import { initws } from './webSocket'
let ws = initws('Hi')
ws.send(...)
ws.onmessage = ev => { console.log(ev.data) }
// SomeComponent.js
import { getws } from './../webSocket'
let ws = getws()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment