websocketServer.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import asyncio
  2. import websockets
  3. import sys
  4. import json
  5. import importlib
  6. import pathlib
  7. import os
  8. async def hello(websocket):
  9. #websocket is a WebSocketServerProtocol
  10. message = await websocket.recv()
  11. host=websocket.remote_address[0]
  12. #delegate parsing to subroutine
  13. #assume the message will be
  14. #pathToPythonCode:argument
  15. #where argument is some sort of a string or a number
  16. #pathToPythonCode can have replacementStrings
  17. #that reflect local software arrangement,
  18. #for example _softwareSrc_ will get replaced by
  19. #software/src directory from setup.json
  20. message=':'.join([host,message])
  21. print(f"<<< FROM: {host}")
  22. print(f"<<< {message}")
  23. greeting = f"Hello {message}!"
  24. run(message)
  25. #await websocket.send(greeting)
  26. #don't send anything, just log
  27. print(f">>> {greeting}")
  28. async def main():
  29. origins=["merlin","labkey-public","onko-nix",None]
  30. #server="vangogh.fmf.uni-lj.si"
  31. server="193.2.68.227"
  32. async with websockets.serve(hello, server, 8765,origins=origins):
  33. await asyncio.Future() # run forever
  34. def run(message):
  35. args=message.split(':')
  36. scriptFile=args[1]
  37. fsetup=os.path.join(os.path.expanduser('~'),'.labkey','setup.json')
  38. with open(fsetup) as f:
  39. setup=json.load(f)
  40. scriptFile=scriptFile.replace('_softwareSrc_',setup['paths']['softwareSrc'])
  41. spath=pathlib.Path(scriptFile)
  42. print('script: {} [{}]{}'.format(scriptFile,spath.parent,spath.stem))
  43. sys.path.append(str(spath.parent))
  44. #print(sys.path)
  45. module=importlib.import_module(spath.stem)
  46. module.main(args[0],args[2])
  47. if __name__ == "__main__":
  48. asyncio.run(main())