websocketServer.py 1.9 KB

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