central.py
This commit is contained in:
9
central.Dockerfile
Normal file
9
central.Dockerfile
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
FROM python:3.8-slim
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
WORKDIR /app
|
||||||
|
RUN pip install --no-cache-dir websockets asyncudp
|
||||||
|
|
||||||
|
COPY central.py /app/
|
||||||
|
STOPSIGNAL SIGINT
|
||||||
|
ENTRYPOINT ["python", "-u", "central.py"]
|
||||||
36
central.py
Normal file
36
central.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
import websockets
|
||||||
|
import asyncudp
|
||||||
|
|
||||||
|
UDP_IP = os.getenv("UDP_IP", "127.0.0.1")
|
||||||
|
UDP_PORT = int(os.getenv("UDP_PORT", 12345))
|
||||||
|
|
||||||
|
async def websocket_handler(websocket):
|
||||||
|
udp_socket = await asyncudp.create_socket(remote_addr=(UDP_IP, UDP_PORT))
|
||||||
|
print("Received new connection from", websocket.remote_address)
|
||||||
|
|
||||||
|
async def forward_to_websocket(udp_socket, websocket):
|
||||||
|
while True:
|
||||||
|
data, addr = await udp_socket.recvfrom()
|
||||||
|
await websocket.send(data)
|
||||||
|
|
||||||
|
task1 = asyncio.create_task(forward_to_websocket(udp_socket, websocket))
|
||||||
|
|
||||||
|
try:
|
||||||
|
async for message in websocket:
|
||||||
|
udp_socket.sendto(message)
|
||||||
|
except websockets.exceptions.ConnectionClosed:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
print("Connection to", websocket.remote_address, "is closed")
|
||||||
|
task1.cancel()
|
||||||
|
udp_socket.close()
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with websockets.serve(websocket_handler, "0.0.0.0", 80):
|
||||||
|
print("WebSocket server started")
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(3600)
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
8
docker-compose.yml
Normal file
8
docker-compose.yml
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
services:
|
||||||
|
ws2udp:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: central.Dockerfile
|
||||||
|
ports:
|
||||||
|
- 80:80
|
||||||
|
restart: always
|
||||||
Reference in New Issue
Block a user