Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how react js acts as a websocket client?

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?

like image 860
ketan Avatar asked Jun 30 '16 11:06

ketan


3 Answers

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.

like image 27
Vinayak Shedgeri Avatar answered Oct 21 '22 09:10

Vinayak Shedgeri


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>;
  }
};
like image 189
pawel Avatar answered Oct 21 '22 08:10

pawel


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>
)}

}

like image 1
AD95 Avatar answered Oct 21 '22 09:10

AD95