简体   繁体   中英

Request handling with React, Redux and Websocket

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM