Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

flask socketio example

// =============================================================== SERVER
from flask import Flask, send_from_directory, request, render_template, session, copy_current_request_context
from flask_cors import CORS
from flask_socketio import SocketIO, emit

app = Flask(__name__)
CORS(app)

socketio = SocketIO(app)
socketio.init_app(app, cors_allowed_origins="*", logger=True, engineio_logger=True)

@socketio.on('connect')
def test_connect(msg):
    print('Connected')


@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')

@socketio.on('messageTestWSS')
def messageTest(msg):
    print('Getting messages: ' + msg)
    emit('messageTestWSS', msg, broadcast=True)
if __name__ == '__main__':
    socketio.run(app, ssl_context=('PATH_TO/fullchain.pem', 'PATH_TO/privkey.pem'), host= '0.0.0.0', port=443, debug=True)

// =============================================================== CLIENT
import { Button } from '@mantine/core'
import React, { useEffect, useState } from 'react'
import io from 'Socket.IO-client'


export default function socket() {
    // const socket = io(process.env.NEXT_PUBLIC_SERVER_URL)
    const [messages, setMessages] = useState(null)
    useEffect(() => {
        socketInitializer()

        // Await a message from the socket
        socket.on('messageTestWSS', (data) => {
            setMessages(data)
        })

    }, [])

    // Setup connection
    const socketInitializer = async () => {
        socket = io(process.env.NEXT_PUBLIC_SERVER_URL)
    }



    return (
        <>
            <input id="inputID" />
            <Button onClick={() => {
                if (socket.connected) {
                    let inputInfo = document.getElementById('inputID')
                    console.log(inputInfo.value)
                    socket.emit('messageTestWSS', inputInfo.value)
                } else {
                    alert('Connection is closed')
                }

            }}>Submit</Button>

            <br />

            <Button color='cyan' onClick={() => {
                // re-setup connection to SOCKET

                socket.connect()

            }}>CONNECT</Button>
            <Button color='red' onClick={() => {
                socket.disconnect()
            }}>DISCONNECT</Button>

            <br />

            <p>{messages}</p>
        </>
    )
}
Comment

websockets socketio flask

<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
    var socket = io();
    socket.on('connect', function() {
        socket.emit('my event', {data: 'I'm connected!'});
    });
</script>
Comment

PREVIOUS NEXT
Code Example
Typescript :: How to pass optional parameters while omitting some other optional parameters? 
Typescript :: angular from date to date validation 
Typescript :: typescript compare types 
Typescript :: +github graphql api get commits from repo 
Typescript :: react native 3 dots icon 
Typescript :: express class validator 
Typescript :: nodejs stream write file 
Typescript :: difference between facets and filters algolia 
Typescript :: how to add enchantments to mobs plugin 
Typescript :: regex exec returns null 
Typescript :: dart clone list 
Typescript :: typescript object literals 
Typescript :: how to pass data to another page in ionic 3 
Typescript :: simple typescript decorator example 
Typescript :: SafeValue must use [property]=binding: 
Typescript :: redux typescript mapdispatchtoprops 
Typescript :: typeorm transaction example 
Typescript :: check null typescript 
Typescript :: slice string into segments of 2 characters 
Typescript :: typescript ingerit 
Typescript :: how to permit only a few values in dbms 
Typescript :: how to git pull all projects in a folder 
Typescript :: typescript keyof type 
Typescript :: all default datasets in seaborn 
Typescript :: submit with data and event in child to parent 
Typescript :: install typeorm ts 
Typescript :: add padding between elements of lazyrow jetpack compose 
Typescript :: They Take Their Medication Then The Device Owner Lets Them Press The Button | The Problem We Are Solving Is Kids Not Taking Their Medication Which Turns To Great Health Benefits In The Young Generation 
Typescript :: Modify the program so it also prints the number of A, T, C, and G characters in the sequence in python 
Typescript :: get localStorage onload page 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =