Browse Source

Modify backend to take Host & Port from envvars and frontend to set them depending on location and NODE_ENV

niels 5 years ago
parent
commit
8d35947b06
2 changed files with 12 additions and 8 deletions
  1. 7 4
      frontend/keezen-frontend/src/util/useWebsocket.js
  2. 5 4
      webserver.py

+ 7 - 4
frontend/keezen-frontend/src/util/useWebsocket.js

@@ -1,4 +1,4 @@
-import React, { useRef, useState, useEffect } from 'react';
+import { useRef, useState, useEffect } from 'react';
 
 export const WebsocketStatus = {
     CONNECTING: "CONNECTING",
@@ -9,9 +9,12 @@ export const WebsocketStatus = {
     DISCONNECTED: "DISCONNECTED",
 }
 
+const IS_PRODUCTION = process.env.NODE_ENV === 'production';
+
 const RETRY_TIMEOUT = 1000;
-const ADDRESS = "127.0.0.1";
-const PORT = 6789;
+const ADDRESS = window.location.hostname;
+const PORT = IS_PRODUCTION ? 6000 : 6789;
+const PROTOCOL = IS_PRODUCTION ? "wss" : "ws";
 
 export default function useWebsocket() {
     const [status, setStatus] = useState(WebsocketStatus.DISCONNECTED);
@@ -25,7 +28,7 @@ export default function useWebsocket() {
             return
         }
 
-        const ws = new WebSocket(`ws://${ADDRESS}:${PORT}`);
+        const ws = new WebSocket(`${PROTOCOL}://${ADDRESS}:${PORT}`);
         ws_ref.current = ws;
         setStatus(WebsocketStatus.CONNECTING);
 

+ 5 - 4
webserver.py

@@ -11,12 +11,13 @@ import random
 import websockets
 from http import HTTPStatus
 
-
-from color import Color
 from option import OptionCode, Option
 from game import Game
 from player import ErrorCode, StateCode, Player
 
+HOST = os.environ.get("KEEZEN_HOST") or "localhost"
+PORT = os.environ.get("KEEZEN_PORT") or 6789
+
 logging.basicConfig()
 
 games = dict()   # code -> game
@@ -151,9 +152,9 @@ if __name__ == "__main__":
 
     static_handler = functools.partial(process_request, os.path.join(os.getcwd(), 'ui'))
 
-    start_server = websockets.serve(handler, "localhost", 6789, process_request=static_handler)
+    start_server = websockets.serve(handler, HOST, PORT, process_request=static_handler)
 
-    print("Running server at http://127.0.0.1:6789/")
+    print(f"Running server at {HOST}:{PORT}")
 
     asyncio.get_event_loop().run_until_complete(start_server)
     asyncio.get_event_loop().run_forever()