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

PREVIOUS NEXT
Code Example
Python :: how to fix Crypto.Cipher could not be resolved in python 
Python :: python convert string to byte array 
Python :: extract tgz files in python 
Python :: python subprocess print stdout while process running 
Python :: Python pandas first and last element of column 
Python :: data series to datetime 
Python :: print specific list item python 
Python :: openpyxl fast tutorial 
Python :: secondary y axis matplotlib 
Python :: thread with args python 
Python :: how to play video in colab 
Python :: render django 
Python :: get name of variable python 
Python :: flask heroku 
Python :: installation of uvicorn with only pure python dependencies 
Python :: pandas nan to none 
Python :: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True) 
Python :: what is from_records in DataFrame() pandas in python? 
Python :: django filter by date range 
Python :: train_test_split sklearn 
Python :: pyspark dropna in one column 
Python :: how to sort a dictionary using pprint module in python 
Python :: pandas index to datetime 
Python :: cv2.namedWindow 
Python :: python slicing nested list 
Python :: what is wsgi 
Python :: selenium get cookies python 
Python :: pathlib path get filename with extension 
Python :: python foreach list 
Python :: python slice a dict 
ADD CONTENT
Topic
Content
Source link
Name
7+5 =