1

I’m developing an application in which I use ReactJS, Redux and Websockets. In this application I’m implementing live rendering feature. (User will get notification on the screen without refreshing the page).

Let’s say I have 2 components which I need to render.

  • Notification
  • Chat

I was thinking of opening 2 separate sockets with accessing 2 separate end points to get data for these 2 components.

Notification Component

componentDidMount() {
    io("sample.data/endpoint/notification").on("data", data => this.setState({notificationData: data}));
}

Chat Component

componentDidMount() {
    io("sample.data/endpoint/chat").on("data", data => this.setState({chatData: data}));
}

Instead of using 2 separate sockets, is there a way which i can do both these functions using 1 socket? In other words, there is an endpoint which retrieves both Notification and Chat data and and after getting that data, is there a way for me to filter and then feed those separate data in to 2 components?

In other words, is there a way to keep a centralized class to handle all the Websocket requests and feed the response to different components?

Let me know your comments regarding this and suggest me a way to approach this.

Kavindu N
  • 383
  • 1
  • 7
  • 23
  • Use just one socket and clasify the messages you send through it. Then you just need to dispatch differents actions depending on the message class you have received. Take a look [here](https://github.com/flarocca/react-redux-websocket/blob/master/src/actions/index.js) line 292 – Facundo La Rocca Apr 20 '17 at 13:22
  • Hi, did you have the chance to take a look at my example? Let me know if you need something else. Thanks. – Facundo La Rocca Apr 20 '17 at 23:45

1 Answers1

0

Unless I'm missing something, what you want to do is correct. Manage one socket and clasify the messages, then dispatch differents actions depending on the message received.

Here you have an implementation as an example:

//Open a connection
static startWebsocketConnection() {
    return new Promise((resolve, reject) => {
      try {
        let W3CWebSocket = require('websocket').w3cwebsocket;
        let client = new W3CWebSocket('ws://localhost:8081/');
        return resolve(client)
      } catch (error) {
        return reject(error)
      }
    })
}

//Dispatch an action depending on the message received
export function openChatWebSocket(chatid) {
  return dispatch => {
    return startWebsocketConnection()
      .then(client => {
        client.onerror = function () { console.log('Connection Error'); };

        client.onopen = function () { console.log('WebSocket Client Connected'); };

        client.onclose = function () { console.log('echo-protocol Client Closed'); };

        client.onmessage = function (e) {
          if (typeof e.data === 'string') {
            let message = JSON.parse(e.data)
            switch (message.event) {
              case 'new-message':
                dispatch(newMessageNotification(message))
                break;

              case 'new-participant':
                dispatch(anotherAction(message))
                break;

              case 'remove-participant':
                dispatch(anotherAction2(message.data.chatid, message.data.participant))
                break;

              default:
                break;
            }
          }
        };
      })
      .catch(error => dispatch(errorOpeningWebsocket(error.message)))
  }
}

//One action as an example
export const newMessageNotification = (message) => {
  return {
    type: 'NEW_MESSAGE_NOTIFICATION',
    message
  }
}

There are two important things when sending or receiving message: Event and Data.

Event usually is a string representing an event (semantic must be given by the bussiness of course) and Data usually is a JSon object containing whatever sent through the socket.

You can take a look at the whole example here and here for an server example using [Node + Express + Socket.io].

You can see the working example here.

Let me know if you need to clarify the example, it is very basic but simple.

Facundo La Rocca
  • 3,786
  • 2
  • 25
  • 47
  • Looking at my repo you will find the whole code working, but I think what you need is [this](https://github.com/theturtle32/WebSocket-Node), I toke this as a tutorial. Then only important thing you need to know is how to receive messages. – Facundo La Rocca Apr 23 '17 at 17:18
  • I think your exmple is ok, but you dont need to open two sockets, one should be enought, from client side you just need a switch to discriminate by event, from server side, use the same socket for everything. – Facundo La Rocca Apr 23 '17 at 17:31
  • Hi @facundo-la-rocca, Thank you very much for this answer. This is exactly what I want but if you can give me a small tutorial or guidance to this, I’ll be much grateful. Thank you. – Kavindu N Apr 24 '17 at 06:19