简体   繁体   中英

convert js code to connect to an existing websocket into a react js app

I have written this js code to connect to my own ruby websocket (two different connections but consider just one. Once connected it waits for a message, parse it and then display a div with some logics (this part is out of scope for now).

   window.onload = function(){
        var documento_da_visionare = '<?php echo $hk; ?>';
        var websocket = new WebSocket('wss://smartscreen.nangapar.com:8443');
        var websocket1 = new WebSocket('wss://smartscreen.nangapar.com:8443');
        var durata = 30;
        websocket.onopen = function(){ 
          //document.title = "VB: " + documento_da_visionare; 
          websocket.send("registra:" + documento_da_visionare);
        } 
        websocket1.onopen = function(){ 
          websocket1.send("registra:allmypage");
        }
        websocket.onmessage = function(evento){
          nome_comando    = evento.data.split(":")[0] 
          valore_comando = evento.data.substr(nome_comando.length + 1); 
          switch (nome_comando){
          //code will continue with the display logics out of scope here

Everything is working fine but I'd like to implement it in React to learn it. I have read many articles and tutorial but I need a "kick" on the right direction refactoring this code. Where should I start from? The most important improvement I'd like to get is to reconnect on disconnection and to display when the client is disconnected. Any hint/help?

You asked couple of questions:

1- How to do re-connect when disconnected and notify user when disconnected:

The best is to use socket.io library, you have to use it on both sides, server and client. It handles both of these cases for you, but if you insist to use pure websocket, you have to ping/pong between the server and client to know if the connection is alive or not, one side triggers, ping, and the other side answers with pong, and the pong side should check with larger interval of the ping to see if it was pinged or not.

2- How to do it in React:

If you are new to reactjs, the path is a bit long. First learn reactjs in general, and then learn the one-directional data flow in react, and then you can use some state-management like MobX. When you get an event from server, you update the state, then the state fire re-render event to UI.

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