paint-brush
Create your own PubSub Client & Server use WebSocketby@tabvn
11,826 reads
11,826 reads

Create your own PubSub Client & Server use WebSocket

by Toan Nguyen DinhApril 15th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Github: <a href="https://github.com/tabvn/pubsub" target="_blank">https://github.com/tabvn/pubsub</a>

Company Mentioned

Mention Thumbnail
featured image - Create your own PubSub Client & Server use WebSocket
Toan Nguyen Dinh HackerNoon profile picture

How it works ?




const pubSub = new PubSubClient('ws://localhost:3001', {connect: true,reconnect: true,})

const topicName = 'abc'  

pubSub.subscribe(topicName, (message) => {  
  console.log(\`Got message from topic ${topicName}\`, message)  
})  

//publish a message to topic  
pubSub.publish(topicName,  
  {title: 'Hello subscribers in the topic abc', body: 'How are you ?'})  

// Broadcast send message to subscribers but not me  
pubSub.broadcast(topicName, {body: 'this is broadcast message'})


// UnsubscribepubSub.unsubscribe(topicName)

Todo@

  • May limit publisher and time to send message if look like spammer
  • Maybe server need wait a time (short time) if detect mutiple publish messages same to one client and send a batch of messages instead of send a single message.
  • Add Crypto client & server key sharing to decrypt between client & server when connected. More security for WebSocket communication. The message from client to server and server to client is encrypted.

Part 1: WebSocket Client and WebSocket Server

Part 2: Subscription : Publish, Subscribe, Broadcast

Part 3: Implement auto reconnect

Part 4: Handle Unsubscribe

Demo

Github: https://github.com/tabvn/pubsub

Video Playlist here