I'm trying to add some functionality to a project which accepts TCP socket connections, to also accept WebSocket connections, but I'm not sure how to best integrate asyncio and threading.
How can I run a WebSocket server and pass the websocket connection on as a socket to be handled by a service in another thread.
from threading import Thread
from bsonrpc import JSONRpc
import websockets
from .myservices import services
def accept(socket):
JSONRpc(socket, services)
def listen(s_socket):
while True:
socket, _ = s_socket.accept()
accept(socket)
def main():
# TCP Socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp_socket.bind(("0.0.0.0", 1234))
tcp_socket.listen(10)
tcp_thread = Thread(target=listen, args=(tcp_socket,), daemon=False)
tcp_thread.start()
# Want to have the same as above but for WebSockets
websocket = ??
websocket_thread = Thread(target=listen, args=(websocket,), daemon=False)
websocket_thread.start()
All the examples I can see for WebSockets pass a handler to the websockets.serve function, but I'm not sure how I would then have a socket I can pass on to the JSONRpc service.
Can anyone help me, or show me if I should be doing this another way?