Git Product home page Git Product logo

socketio-shared-webworker's Introduction

Socket.io inside a shared WebWorker

Running Socket.io in a shared webworker allows you to share a single Socket.io websocket connection for multiple browser windows and tabs. A drop in replacement for the socket.io client.

Quick Install

npm i --save socketio-shared-webworker

Reason

  • It's more efficient to have a single websocket connection
  • Page refreshes and new tabs already have a websocket connection, so connection setup time is zero
  • The websocket connection runs in a separate thread/process so your UI is 'faster'
  • Cordination of event notifications is simpler as updates have a single source
  • Can be extended as a basis for IPC between your browser windows/tabs
  • It's the cool stuff..

Current Support

The aim is to support all methods from Socket.io client API. https://github.com/socketio/socket.io-client/blob/master/docs/API.md

All events to/from socket.io will be forwarded by the webworker.

Subscribe to events io.on('event', fn) is a local for each tab/window

Emit any event/obj io.emit('event', {data: 'blalba'}). Missing acknowledgement callback param atm.

Connect and disconnect io.emit('connect', fn) is broadcasted to all tabs/windows

Connection Manager io.Manager is not yet supported

var ws = wio('http://localhost:8000/')
ws.start() // use default SharedWorker script URL

// same as socket.io-client api: https://github.com/socketio/socket.io-client
ws.on('connect', () => {
    console.log('connected!')
    ws.emit('message', 'Hi There!')
})
ws.on('message', data => console.log('received message', data))
ws.on('disconnect', () => console.log('disconnected!'))
ws.on('error', data => console.log('error', data))

Install

Install locally using npm. (Alternatively clone the repo and look at index.html as an example)

npm install --save socketio-shared-webworker

To use in your nodejs project:

var wio = require('socketio-shared-webworker')
var ws = wio('http://localhost:8000/')
ws.start() // use default SharedWorker script URL

// same as socket.io-client
ws.on('connect', () => {
    console.log('connected!')
    ws.emit('message', 'Hi There!')
})

ws.on('message', data => console.log('received message', data))
ws.on('disconnect', () => console.log('disconnected!'))
ws.on('error', data => console.log('error', data))

To use in HTML wio is global.

<script src="socket.io-worker.js"></script>
<script>
var ws = wio('http://localhost:8000/')
ws.start() // use default SharedWorker script URL

// same as socket.io-client
ws.on('connect', () => {
    console.log('connected!')
    ws.emit('message', 'Hi There!')
})
ws.on('message', data => console.log('received message', data))
ws.on('disconnect', () => console.log('disconnected!'))
ws.on('error', data => console.log('error', data))
</script>

Using a specific SharedWorker script

When using ws.start() the default worker located in build/shared-worker-inline.js is used. This worker is served inline using URL.createObjectURL() instead of being served over HTTP. This is limited to Worker and SharedWorker since ServiceWorker requires the same domain. (ServiceWorker is not supported)

In order to specify the Worker script URL manually use:

ws.useWorker('http/same/domain/url/to/shared-worker.js')

Note: ws.useWorker('shared-worker.js') should point to the shared-worker.js url relative to your HTML page base URL. Shared webworkers can only be loaded from the same domain similar to CORS. When installed into a project with npm i socketio-shared-webworker you will find the script in: node_modules/socketio-shared-webworker/build/shared-worker.js

You may copy dist/shared-worker.js to your public/ directory and serve using express.static. An example of this is found in server.js. You can also serve it as a regular JS file with Apache, Nginx etc.

var wio = require('socketio-shared-webworker')
var ws = wio('http://localhost:8000/')
ws.useWorker('shared-worker.js') // use a specific SharedWorker script URL
// same as socket.io-client

Using a Worker instead of SharedWorker

By default the library will use Worker when SharedWorker is not available. If you want to specify using Worker specifically then use:

var wio = require('socketio-shared-webworker')
var ws = wio('http://localhost:8000/')
ws.setWorkerType(Worker)
ws.start()
// same as socket.io-client

At the moment only SharedWorker and Worker are supported.

ServiceWorker is not supported since it is short lived.

Please create an issue if you have a use case for ServiceWorker.

Develop

git clone https://github.com/IguMail/socketio-shared-webworker
cd socketio-shared-webworker
npm install
# Start example/dev-server.js with HMR
npm run dev
# edit example/app.js, src/shared-worker.js, src/socket.io-worker.js etc.

In chrome visit the URL: chrome://inspect/#workers so see shared webworkers and inspect, debug. Visit the index.html in the browser for the demo.

Test

git clone https://github.com/IguMail/socketio-shared-webworker
cd socketio-shared-webworker
npm install
# Start development server with HMR
npm run dev
# Run unit tests
npm test 
# Run e2e tests
npm run test:e2e

Production build

npm run build

The builds will be placed in build/ directory. Copy these to your public/ directory in your server.

Production usage

The public/index.html is an example of usign the production build.

Start the production sample server.js with:

npm start

Based heavily on

Thanks to.

https://gonzalo123.com/2014/12/01/enclosing-socket-io-websocket-connection-inside-a-html5-sharedworker/

https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

https://www.sitepoint.com/javascript-shared-web-workers-html5/

socketio-shared-webworker's People

Contributors

dependabot[bot] avatar fijiwebdesign avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socketio-shared-webworker's Issues

Is it possible to use this library with webpack?

I have an error wile importing lib like this in angular 9 project
import * as io from 'socketio-shared-webworker';
or
const wio = require('socketio-shared-webworker');

Module parse failed: Unexpected token (9:15)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class SharedWorkerSocketIO {
|
>     WorkerType = global.SharedWorker || global.Worker
|     worker = null
|     workerUri = null
i 「wdm」: Failed to compile.

Suggestions of improvements

I understand the idea of console.loging everything, but only in devMode, would be nice to have a (boolean) var devMode = false that if you turn on, it will output console logs...

Would be nice to suggest an implementation like this (support safari/ie-edge ):

var socket;
if (typeof(window.SharedWorker) === 'undefined') {
  socket = io('http://localhost:50180/fiep-crm');
} else {
  socket = wio('http://localhost:50180/fiep-crm');
  socket.setWorker('js/shared-worker.js');
}

and with this, suggest the user not to use send(msg), only emit('message', msg).

I was struggling doing some code (based in an article that you based your work here) trying to send a message (send()), but this seems far better, I'm only worried that since it doesn't use the socket.io's lib, that it may get outdated...

Use service worker ?

Support for service worker is better than shared worker, and i believe it should be possible to implement a shared socketio connection using the service worker in a totally transparent way ?

Why not support options in socket.io ?

In src/socketio-worker.js

...
 constructor(socketUri, options) {
        this.log('SharedWorkerSocketIO ', socketUri)
        this.socketUri = socketUri
        // add below
        this.options = options
    }

    startSocketIo() {
       // this.socket = io(this.socketUri)
       this.socket = io(this.socketUri, options)
    }
...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.