Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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

flask socketio usage

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

if __name__ == '__main__':
    socketio.run(app)
Comment

flask socketio send

from flask_socketio import send

@socketio.on('message')
def handle_message(message):
    send(message)
Comment

PREVIOUS NEXT
Code Example
Python :: random forest 
Python :: id() python 
Python :: selenium 
Python :: stdin and stdout in python 
Python :: Python How To Convert a String to Variable Name 
Python :: how to add virtual environment in vscode 
Python :: sum 2d array in python 
Python :: python3 create list from string 
Python :: python len 
Python :: How to perform heap sort, in Python? 
Python :: cross entropy 
Python :: How to select element using xpath in python 
Python :: python key 
Python :: if we use list in the dictionary 
Python :: add key to dictionairy 
Python :: avoid self python by making class functions static 
Python :: del en python 
Python :: python press any key to continue 
Python :: reading an image using opencv library 
Python :: how to convert one dimensional array into two dimensional array 
Python :: csv.dictreader 
Python :: python function to do comparison between two numbers 
Python :: print numbers from 1 to 100 in python 
Python :: gui with pygame 
Python :: python os check if file with extension exists 
Python :: diccionario python 
Python :: print something python 
Python :: how to remove text in pygame 
Python :: pandas dataframe total column 
Python :: how to get value_counts() order 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =