PYTHON   64
socketio Server
Guest on 25th August 2023 12:09:17 PM


  1. import socketio
  2. import socket
  3. import json
  4. import re
  5. import threading
  6. import eventlet
  7.  
  8. sio = socketio.Server(cors_allowed_origins='*')
  9. app = socketio.WSGIApp(sio)
  10.  
  11. @sio.event
  12. def connect(sid, environ):
  13.     print('Client connected:', sid)
  14.  
  15. @sio.event
  16. def disconnect(sid):
  17.     print('Client disconnected:', sid)
  18.  
  19. @sio.on('message')
  20. def handle_message(sid, data):
  21.     print('Received message:', data)
  22.     sio.emit('message', 'from server: lorem-ispsum', room=sid)
  23.  
  24. def read_from_udp():
  25.     UDP_IP = '127.0.0.1'
  26.     UDP_PORT = 8080
  27.     server_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  28.     server_sock.bind((UDP_IP, UDP_PORT))
  29.  
  30.     while True:
  31.         data, _ = server_sock.recvfrom(1024)
  32.         data = data.decode("utf-8")
  33.         print(data)
  34.         p = re.compile('(?<!\)'')
  35.        data = p.sub('"', data)
  36.        print(data)
  37.        sio.emit("data", {'data': data})
  38.  
  39. def start_udp_thread():
  40.    udp_thread = threading.Thread(target=read_from_udp)
  41.     udp_thread.daem
  42.    udp_thread.start()
  43.  
  44. def start_socketio_server():
  45.    eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 8081)), app)
  46.  
  47. if __name__ == '__main__':
  48.    udp_thread = threading.Thread(target=start_udp_thread)
  49.    socketio_thread = threading.Thread(target=start_socketio_server)
  50.    udp_thread.start()
  51.    socketio_thread.start()
  52.    udp_thread.join()
  53.    socketio_thread.join()

Raw Paste

Login or Register to edit or fork this paste. It's free.