Skip to content

Instantly share code, notes, and snippets.

@woraperth
Last active April 6, 2024 20:56
Show Gist options
  • Save woraperth/3ecb45fe3b6502cabae043ba9fd3a3e5 to your computer and use it in GitHub Desktop.
Save woraperth/3ecb45fe3b6502cabae043ba9fd3a3e5 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()
@vixchauhan
Copy link

I have used this library for re-connection sockets when server disconnected, but what i want is when server is disconnected and reconnected then i want to send the previous request in order to get the current screen response(last ws.send function response), if you find any thing regarding this please let me know.

Websocket Reconnect

@woraperth
Copy link
Author

Thanks for sharing this!
For your case of submitting the previous request, you might be able to use try { } catch { } blocks to record the failed request so that you can send them again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment