'Django as a websocket client
I know that Django Channels can be used to make websocket server, not client. So I used websockets to relay websocket incoming message to my Django like this:
async def relay():
source_server = 'ws://source.example/ws/message' # This is an external server
target_server = 'ws://target.example/ws/message' # This is my Django server
async for target in websockets.connect(target_server):
try:
async for source in websockets.connect(source_server):
try:
while True:
try:
message = await source.recv()
await target.send()
# log message
except websockets.ConnectionClosed as e:
# lost source server or target server or both
raise(e)
except Exception as e:
# did not lose servers
continue
except websockets.ConnectionClosed as e:
# lost source server or target server or both
if target.close_code is not None:
# lost target server and need to start from the outer for loop
# (to get a new target websocket connection)
source.disconnect()
raise(e)
# lost source server and will continue the inner for loop
# (to get a new source websocket connection)
continue
except Exception as e:
# did not lose any server and will continue the inner for loop
# (to get a new source websocket connection)
continue
except websockets.ConnectionClosed as e:
# lost target server and will continue the outer for loop
# (to get a new target websocket connection)
continue
except Exception as e:
# did not lose any server and will start the outer for loop
# (to get a new target websocket connection)
continue
asyncio.run(relay())
Understandably, this is not the most efficient code-up. But this is what I can think of. I run this code as a Docker container (let's call it relay container) along side with my Django Docker containers (with the same Docker image as Django of course).
Here's my questions:
- Is there a way to make Django a websocket client? (I want to save one container for the relay). For your information, I run Django container (using Daphne), two Celery (one for beat and one for worker) containers.
- If I bring down the relay container, it takes long time (five to ten seconds) to be down. The exit code is Out Of Memory. What causes the problem? How can I shutdown the container gracefully?
Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
