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 w
So a very basic example without much overhead would require two things:
a component with a reference to websocket connection
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>;
}
};
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.
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>
)}
}