Przykład Socketio Flask
// =============================================================== 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>
</>
)
}
Talhah Patelia