websocketServer.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. print(f"Starting server at {server}")
  34. async with websockets.serve(hello, server, 8765,origins=origins):
  35. await asyncio.Future() # run forever
  36. def run(message):
  37. args=message.split(':')
  38. scriptFile=args[1]
  39. fsetup=os.path.join(os.path.expanduser('~'),'.labkey','setup.json')
  40. with open(fsetup) as f:
  41. setup=json.load(f)
  42. parts=scriptFile.split('/')
  43. scriptDir=parts[-2]#one before last, last is the script name
  44. scriptFile=scriptFile.replace('_softwareSrc_',setup['paths']['softwareSrc'])
  45. venv=setup['venv'][scriptDir]
  46. pCall=os.path.join(venv,'bin','python')
  47. argsCall=[pCall,scriptFile,args[0],args[2]]
  48. subprocess.run(argsCall)
  49. #spath=pathlib.Path(scriptFile)
  50. #print('script: {} [{}]{}'.format(scriptFile,spath.parent,spath.stem))
  51. #sys.path.append(str(spath.parent))
  52. #print(sys.path)
  53. #module=importlib.import_module(spath.stem)
  54. #module.main(args[0],args[2])
  55. if __name__ == "__main__":
  56. asyncio.run(main())