sgcWebSockets and React client

sgcWebSockets library fully supports RFC6455, so any client that supports this RFC will be able to connect to our servers.

You can connect with REACT to sgcWebSockets library without problems, just create a new class which implements WebSocket class and use it to connect, send messages, receive messages from server...

React WebSocket Example

 In order to use WebSocket protocol in React, you must use instantiate WebSocket class, passing websocket url as argument (example: ws://echo.websocket.org) and then bind websocket events to be notified when socket is connected, disconnected or a new message arrives. Find below a very simple sample react code, which shows how connect to a websocket server and send a message after a successful connection.

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>
        );
    }
} 

ASP.NET Core React Example 

 You can build React Apps using ASP .NET Core, find below a link to download a full Visual Studio Project, showing a demo that connects to our secure websocket server chat.

https://www.esegece.com/download/sgcWebSocketsReact.zip

×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

COVID-19
Google Cloud Pub/Sub Delphi Component

Related Posts