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 socket io

pip install flask-socketio
Comment

flask socketio usage javascript

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" 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

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 socket io

gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 module: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 :: fizz buzz 
Python :: replace nan 
Python :: open pdfs using python 
Python :: pandas create average per group 
Python :: python encode file 
Python :: python list add to start 
Python :: dict column to be in multiple columns python 
Python :: get first letter of each word in string python 
Python :: brute force string matching algorithm in python 
Python :: creating a python virtual environment 
Python :: structure ternaire python 
Python :: ip address finder script python 
Python :: from django.core.management import execute_from_command_line ImportError: No module named django.core.management 
Python :: python filter list with lambda 
Python :: help() function in python 
Python :: python logical operators 
Python :: python clear stdout 
Python :: python try catch print stack 
Python :: condition python 
Python :: dict to string 
Python :: pygame scroll event 
Python :: How to sort a Python dict by value 
Python :: get request in django 
Python :: %s in python 
Python :: cookies in django 
Python :: selenium python tkinter 
Python :: python program to find sum of natural numbers using recursion 
Python :: ngnix config 
Python :: Adding new column to existing DataFrame in Pandas using assign method 
Python :: python svg viewing 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =