Skip to content

Commit

Permalink
Remove websocket in favor of aiohttp
Browse files Browse the repository at this point in the history
Signed-off-by: yzamir <kobi.zamir@gmail.com>
  • Loading branch information
yaacov committed Sep 13, 2023
1 parent f4b422c commit f911553
Show file tree
Hide file tree
Showing 9 changed files with 29 additions and 33 deletions.
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ Build the Docker image:

Run the Docker image on port 8880:

podman run -it --rm --name=rose_server -p 8880:8880 -p 8765:8765 rose_server
podman run -it --rm --name=rose_server -p 8880:8880 rose_server

If you don't want to see the log of the run in the current window,
replace `-it` with `-d`.
Expand All @@ -113,7 +113,7 @@ game.
You can use SSH tunneling when running the server on your remote VM, so
you can view the game in you local browser:

ssh -L 8880:127.0.0.1:8880 -L 8765:127.0.0.1:8765 {user}@{server-address}
ssh -L 8880:127.0.0.1:8880 {user}@{server-address}

After starting the server (as mentioned above), open a browser at
http://127.0.0.1:8880/ to view and control the game.
Expand All @@ -125,7 +125,6 @@ server, and browse from a local machine in case port 8880 or 8888 are
blocked by [firewalld](https://firewalld.org/):

sudo firewall-cmd --add-port=8880/tcp --permanent
sudo firewall-cmd --add-port=8765/tcp --permanent
sudo firewall-cmd --reload

## Running a driver
Expand Down
1 change: 0 additions & 1 deletion rose/server/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

IMAGE_NAME ?= quay.io/rose/rose-server
PORT ?= 8880
WS_PORT ?= 8765

# Default driver when running on localhost
DRIVERS ?= http://127.0.0.1:8081
Expand Down
2 changes: 1 addition & 1 deletion rose/server/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Instructions:

.. code-block:: bash
kubectl port-forward deployment/rose-engine-deployment 8880:8880 8765:8765
kubectl port-forward deployment/rose-engine-deployment 8880:8880
Now, the service will be accessible locally at http://localhost:8880.

Expand Down
2 changes: 1 addition & 1 deletion rose/server/game/net.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,6 @@ async def send_to_all_websockets(data, active_websockets):
json_encoded_data = json.dumps(data)
for ws in active_websockets:
try:
await ws.send(json_encoded_data)
await ws.send_str(json_encoded_data)
except Exception as e:
log.error("Fail ws send", e)
39 changes: 23 additions & 16 deletions rose/server/game/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import os

import aiohttp
import websockets
from aiohttp import web

from common import config
Expand Down Expand Up @@ -62,28 +61,36 @@ async def admin_handler(request):
return web.Response(text=json.dumps(state))


async def websocket_handler(websocket, path):
async def websocket_handler(request):
"""
Handle websocket connections, sending a greeting to the client.
Handle WebSocket connections, echoing received messages with a prefix.
Args:
websocket (websockets.WebSocketServerProtocol): The websocket protocol instance.
path (str): The path the client connected to.
request (aiohttp.web.Request): The request object.
Returns:
aiohttp.web.WebSocketResponse: The WebSocket response object.
"""
active_websockets.add(websocket)
ws = web.WebSocketResponse()
await ws.prepare(request)

active_websockets.add(ws)
try:
async for message in websocket:
# Handle or respond to the message if necessary
await websocket.send(f"Received: {message}")
except Exception as e:
print(f"WebSocket error: {e}")
async for msg in ws:
if msg.type == web.WSMsgType.TEXT:
response_message = f"Received: {msg.data}"
await ws.send_str(response_message)
elif msg.type == web.WSMsgType.ERROR:
print(f"WebSocket error: {ws.exception()}")
finally:
active_websockets.remove(websocket)
active_websockets.remove(ws)
await ws.close()

return ws


async def run(
http_port,
ws_port,
listen_address,
initial_rate,
initial_running,
Expand Down Expand Up @@ -120,9 +127,12 @@ async def run(
async def index_handler(request):
return web.FileResponse(os.path.join(public, "index.html"))

# Add application routes
app.router.add_get("/", index_handler)
app.router.add_get("/ws", websocket_handler)
app.router.add_post("/admin", admin_handler)

# Add public static routes
app.router.add_static("/res/", path=theme, name="theme")
app.router.add_static("/", path=public, name="static")

Expand All @@ -133,9 +143,6 @@ async def index_handler(request):
# Start HTTP server
await site.start()

# Start websocket server
await websockets.serve(websocket_handler, listen_address, ws_port)

print(f"Theme {theme}")
print(f"Track {track_type}")
print(f"Drivers {initial_drivers}")
Expand Down
4 changes: 0 additions & 4 deletions rose/server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ def main():
parser.add_argument(
"-p", "--port", type=int, default=8880, help="Port for HTTP server"
)
parser.add_argument(
"--ws-port", type=int, default=8765, help="Port for WebSocket server"
)
parser.add_argument(
"--listen", default="127.0.0.1", help="Listening address for servers"
)
Expand Down Expand Up @@ -59,7 +56,6 @@ def main():
loop.run_until_complete(
server.run(
args.port,
args.ws_port,
args.listen,
args.initial_rate,
args.running,
Expand Down
1 change: 0 additions & 1 deletion rose/server/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# requirements.txt

requests>=2.28.0
websockets>=11.0.0
aiohttp>=3.8.0
6 changes: 1 addition & 5 deletions rose/server/rose-engine.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,4 @@ spec:
protocol: TCP
port: 8880
targetPort: 8880
- name: ws
protocol: TCP
port: 8765
targetPort: 8765
type: LoadBalancer # run outside the cluster: kubectl port-forward service/rose-server-service 8880:8880 8765:8765 .
type: LoadBalancer # run outside the cluster: kubectl port-forward service/rose-server-service 8880:8880 .
2 changes: 1 addition & 1 deletion rose/server/web/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ class Client {
}

connect() {
var wsuri = `ws://${window.location.hostname}:8765/ws`;
var wsuri = `ws://${window.location.host}/ws`;
console.log("Connecting to " + wsuri);
this.socket = new WebSocket(wsuri);
this.socket.onopen = (e) => {
Expand Down

0 comments on commit f911553

Please sign in to comment.