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