import React from 'react';
/*import logo from './logo.svg';*/
import './App.css';
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
ws: null
};
}
// single websocket instance for the own application and constantly trying to reconnect.
componentDidMount() {
this.connect();
}
timeout = 250; // Initial timeout duration as a class variable
/**
* @function connect
* This function establishes the connect with the websocket and also ensures constant reconnection if connection closes
*/
connect = () => {
var ws = new WebSocket("wss://5.196.65.55:8443");
let that = this; // cache the this
var connectInterval;
// websocket onopen event listener
ws.onopen = () => {
console.log("connected websocket main component");
this.setState({ ws: ws });
that.timeout = 250; // reset timer to 250 on open of websocket connection
clearTimeout(connectInterval); // clear Interval on on open of websocket connection
};
// websocket onclose event listener
ws.onclose = e => {
console.log(
`Socket is closed. Reconnect will be attempted in ${Math.min(
10000 / 1000,
(that.timeout + that.timeout) / 1000
)} second.`,
e.reason
);
that.timeout = that.timeout + that.timeout; //increment retry interval
connectInterval = setTimeout(this.check, Math.min(10000, that.timeout)); //call check function after timeout
};
// websocket onerror event listener
ws.onerror = err => {
console.error(
"Socket encountered error: ",
err.message,
"Closing socket"
);
ws.close();
};
};
/**
* utilited by the @function connect to check if the connection is close, if so attempts to reconnect
*/
check = () => {
const { ws } = this.state;
if (!ws || ws.readyState == WebSocket.CLOSED) this.connect(); //check if websocket instance is closed, if so call `connect` function.
};
render() {
return <ChildComponent websocket={this.state.ws} />;
}
}
class ChildComponent extends React.Component {
sendMessage=()=>{
const {websocket} = this.props // websocket instance passed as props to the child component.
try {
//websocket.send(data) //send data to the server
websocket.send("registra:a1b2c3d4e5f");
} catch (error) {
console.log(error) // catch error
}
}
receiveMessage=()=>{
const {websocket} = this.props // websocket instance passed as props to the child component.
websocket.onmessage=function(evento){console.log(evento.data);};
}
render() {
return (
<div id="ricevuto">
........
</div>
);
}
}
export default ChildComponent;
На данный момент это мой код для создания компонента реакции, который подключается к существующей веб-розетке и прослушивает сообщения, отправленные веб-сокетом. В настоящее время у меня есть две проблемы: не установлено соединение с сервером, сообщение не получено
клиенту необходимо отправить websocket.send("registra:a1b2c3d4e5f");
, чтобы зарегистрироваться на сервере и открыть канал. Любая помощь приветствуется!