Anonymous User
  Monday, 23 March 2020
  3.4K Visits
  Subscribe
Would you have an example for client in React to consume a sgc websocket server?
4 years ago
·
#262
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
  • Page :
  • 1
There are no replies made for this post yet.
Sorry, the discussion is currently locked. You will not be able to post a reply or a comment at the moment.
Submit Your Response
Upload files or images for this discussion by clicking on the upload button below.
Supported: gif,jpg,png,jpeg,zip,rar,pdf
· Insert · Remove
  Upload Files (Maximum 10MB)