Skip to content

Commit

Permalink
feat(server): send IP in announcement
Browse files Browse the repository at this point in the history
discover_games function in UI to list all games

Co-Authored-By: Bengt Wegner <[email protected]>
  • Loading branch information
JM-Lemmi and Petzys committed Mar 18, 2024
1 parent a25335c commit c87f27a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
4 changes: 3 additions & 1 deletion Server/websocket_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from jsonschema import validate, ValidationError
import uuid
from zeroconf import ServiceInfo, Zeroconf
import socket

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
Expand All @@ -30,7 +31,8 @@ def __init__(self, admin:Player, port: int = 8765) -> None:
# MDNS
#https://stackoverflow.com/a/74633230
self._mdns = Zeroconf()
wsInfo = ServiceInfo(type_ = '_tictactoe._tcp.local.', name = 'tttk-'+str(uuid.uuid4())+'._tictactoe._tcp.local.', port = self._port)
ip = socket.inet_aton(socket.gethostbyname(socket.gethostname())) # this is a dirty hack and also doesnt work dual stack :'(
wsInfo = ServiceInfo(type_ = '_tictactoe._tcp.local.', name = admin.display_name+'s-Server'+'._tictactoe._tcp.local.', port = self._port, addresses = [ip])
self._mdns.register_service(wsInfo)


Expand Down
42 changes: 42 additions & 0 deletions UI/autodiscovery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from zeroconf import ServiceBrowser, ServiceListener, Zeroconf
import logging
import time

logger = logging.getLogger(__name__)

def discover_games(timeout: int = 5) -> dict:
"""
Returns a dictionary of games that are available to play.
The key is the name of the game and the value is the IP address of the server as string.
param: timeout. The time in seconds to wait for responses. Default is 5 seconds.
return: dict. A dictionary of games on the network that are available to play. Key is the name, Value is the IP as string.
"""

class MyListener(ServiceListener):
def __init__(self):
self.results = {}

def add_service(self, zc: Zeroconf, type_: str, name: str) -> None:
info = zc.get_service_info(type_, name)
if info:
logger.info(f"Service {name} found, service address: {info.parsed_addresses()[0]}") # TODO only gets first address, so dual stack is not possible
self.results.update({name.removesuffix('._tictactoe._tcp.local.'): info.parsed_addresses()[0]})
else:
logger.error(f"Service {name} found, no info")


zeroconf = Zeroconf()
listener = MyListener()
ServiceBrowser(zeroconf, "_tictactoe._tcp.local.", listener)

time.sleep(timeout)

zeroconf.close()
return listener.results

if __name__ == "__main__":
while True:
print(discover_games())
time.sleep(5)

0 comments on commit c87f27a

Please sign in to comment.