By Guest on Monday, 23 March 2020
Posted in General
Likes 0
Views 3.8K
Votes 0
Would you have an example for client in React to consume a sgc websocket server?
You can use the following sample code, it opens a connection to localhost server listening port 5414.
When connects to server, sends the message "Message from react".


import React, { Component } from 'react';

export class sgcWebSockets extends Component {
static displayName = sgcWebSockets.name;

constructor(props) {
super(props);
this.ws = WebSocket
this.websocketOpen = this.websocketOpen.bind(this);
}

websocketOpen() {

this.ws = new WebSocket('ws://localhost:5414')

this.ws.onopen = () => {
// connected
this.ws.send('Message from react')
}
this.ws.onmessage = evt => {
// listen to data sent from the websocket server
const message = JSON.parse(evt.data)
}

this.ws.onclose = () => {
// disconnected
}
}

render() {
return (
<div>
<h1>sgcWebSockets</h1>
<button className="btn btn-primary" onClick={this.websocketOpen}>Connect</button>
</div>
);
}
}


Kind regards,
Sergio
·
4 years ago
·
0 Likes
·
0 Votes
·
0 Comments
·
View Full Post