Last active
June 3, 2021 12:57
-
-
Save IgniparousTempest/376a04466d8dfe1f497b2e8852a0ad61 to your computer and use it in GitHub Desktop.
Python SocketIO server to server communication: socketIO-client to Flask-SocketIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from socketIO_client import SocketIO, BaseNamespace | |
class ChatNamespace(BaseNamespace): | |
def on_connect(self): | |
print('connect') | |
self.emit('message', {'author': 'Client', 'message': {'author': 'Client', 'message': 'Hello, Server!'}) | |
def on_disconnect(self): | |
print('disconnect') | |
def on_reconnect(self): | |
print('reconnect') | |
def on_response(self, msg): | |
print('{}: {}'.format(msg['author'], msg['message'])) | |
socketIO = SocketIO('localhost', 6666) | |
chat_namespace = socketIO.define(ChatNamespace, '/chat') | |
chat_namespace.emit('message', {'author': 'Client', 'message': 'Server, are you there?'}) | |
socketIO.wait(seconds=1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request | |
from flask_socketio import SocketIO, emit | |
app = Flask(__name__) | |
socketio = SocketIO(app) | |
socketio_connections = set() | |
@socketio.on('message', namespace='/chat') | |
def chat_message(msg): | |
print('{}: {}'.format(msg['author'], msg['message'])) | |
emit('response', {'author': 'Server', 'message': 'I heard you, Client :)'}) | |
@socketio.on('connect', namespace='/chat') | |
def on_connect(): | |
socketio_connections.add(request.sid) | |
print('Session created: {}'.format(request.sid)) | |
@socketio.on('disconnect', namespace='/chat') | |
def on_disconnect(): | |
socketio_connections.remove(request.sid) | |
print('Session disconnected: {}'.format(request.sid)) | |
if __name__ == '__main__': | |
socketio.run(app, host='0.0.0.0', port=6666) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment