Source:  Twitter logo

I want to create a Websocket based client-server Application. In that I'm created node js websocket server which is waiting for the clients. Now I want to create react js websocket client. I'm using react js as a websocket because I have to render elements continuously which server sends as a simple text message.

I'm struck at implementing the react js as a websocket client. How it should work as a websocket client and how it will send request to the websocket server just like this :

'ws://localhost:1234'

I want to know more about websocket client and also want to solve this issue?

So a very basic example without much overhead would require two things:

  1. a component with a reference to websocket connection

  2. an event listener on the connection that updates the state of the component when a message arrives

Demo: http://jsfiddle.net/69z2wepo/47360/
Demo (2019): http://jsfiddle.net/643atLce/

class Echo extends React.Component {
    constructor(props){
    super(props);
    this.state = { messages : [] }
  }

  componentDidMount(){
    // this is an "echo" websocket service
    this.connection = new WebSocket('wss://echo.websocket.org');
    // listen to onmessage event
    this.connection.onmessage = evt => { 
      // add the new message to state
        this.setState({
        messages : this.state.messages.concat([ evt.data ])
      })
    };

    // for testing purposes: sending to the echo service which will send it back back
    setInterval( _ =>{
        this.connection.send( Math.random() )
    }, 2000 )
  }

  render() {
    // slice(-5) gives us the five most recent messages
    return <ul>{ this.state.messages.slice(-5).map( (msg, idx) => <li key={'msg-' + idx }>{ msg }</li> )}</ul>;
  }
};
30 users liked answer #0dislike answer #030
pawel profile pic
pawel

Just create rest program from server side and create the connection at a Web page.

var connection = new WebSocket('ws://localhost/echo', ['soap', 'xmpp']);

opening the connection 
connection.onopen = function () {
  connection.send('Ping'); // 
};


connection.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

//to receive the message from server
connection.onmessage = function (e) {
  console.log('Server: ' + e.data);
};

// Sending String  
connection.send('your message');

At server side you will get session and message, So you can do communication with N sessions.

1 users liked answer #1dislike answer #11
Vinayak Shedgeri profile pic
Vinayak Shedgeri

In your react Project folder in App.js add a websocket connection & listen for the messages coming from the websocket server.

class App extends React.Component{
  constructor(){
   super();
    this.state={
      endpoint:"ws://localhost:1234",
      messages:[]
     }
   }

  componentDidMount(){
  //initialize connection
   const ws = new WebSocket(this.state.endpoint)
    ws.onopen = () =>{
     //send any msg from Client if needed
       ws.send(JSON.stringify(temp))
  }
   //save whatever response from client
    ws.onmessage = evt =>{
     this.setState({
      message:this.state.message.concat(evt.data)
    })
  }
 }
 render(){
 return(
 <div>
 <p>{this.state.message.map(items=><li>{items}</li>)}</p>
 </div>
)}

}

1 users liked answer #2dislike answer #21
AD95 profile pic
AD95

I leave here a Functional Example (all of the above are Objects...)

const client = new WebSocket(ws://stream.marketpricesfun.com)
const [cottonPrice, setCottonPrice] = useState(0)

useEffect(() => {
    client.onopen = () => {
        client.send('{"topic": "subscribe", "to": "newPrices"}')
    }

    client.onmessage = (message) => {
        if (message.data) {
            const parsedData = JSON.parse(message.data)

            setCottonPrice(parsedData.cotton.price)
        }
    }

    return () => {
        client.close()
    }
}, [])
0 users liked answer #3dislike answer #30
Ari Waisberg profile pic
Ari Waisberg

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).