Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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

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

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
Javascript :: classlist.toggle 
Javascript :: jquery array 
Javascript :: bootstrap js, jQuery, popper cdn 
Javascript :: clear whitespace from object javascript 
Javascript :: how to loop through array of numbers in javascript 
Javascript :: vue shortcut to create component 
Javascript :: javascript add days to date 
Javascript :: open gz file node 
Javascript :: redux persist a non-serializable value was detected in an action in the path register 
Javascript :: array contains object in javascript 
Javascript :: change page title js 
Javascript :: javascript pass all arguments to another function 
Javascript :: how do i listen to a keypress in javascript 
Javascript :: change value of drop down using jquery 
Javascript :: javascript onclick to another page div 
Javascript :: radio button set value in javascript 
Javascript :: javascript undefined check 
Javascript :: formik stepper form 
Javascript :: javascript truncate array 
Javascript :: make contenteditable false javascript 
Javascript :: binary to int javascript 
Javascript :: date-and-time npm 
Javascript :: hello word in js 
Javascript :: js input hidden get value 
Javascript :: javascript map Removing Elements 
Javascript :: how to edit website 
Javascript :: js how to print 
Javascript :: global error handling middleware express 
Javascript :: sort array of object by another value array in javascript 
Javascript :: check scroll top height in react js 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =