MCPcopy Create free account
hub / github.com/emscripten-core/emscripten / WebsockifyServerHarness

Class WebsockifyServerHarness

test/test_sockets.py:93–156  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

91
92
93class WebsockifyServerHarness:
94 def __init__(self, filename, args, listen_port, do_server_check=True):
95 self.processes = []
96 self.filename = filename
97 self.listen_port = listen_port
98 self.target_port = listen_port - 1
99 self.args = args or []
100 self.do_server_check = do_server_check
101
102 def __enter__(self):
103 try:
104 import websockify # type: ignore
105 except ModuleNotFoundError:
106 raise Exception('Unable to import module websockify. Run "python3 -m pip install websockify" or set environment variable EMTEST_SKIP_PYTHON_DEV_PACKAGES=1 to skip this test.') from None
107
108 # compile the server
109 # NOTE empty filename support is a hack to support
110 # the current test_enet
111 if self.filename:
112 cmd = [CLANG_CC, test_file(self.filename), '-o', 'server', f'-DSOCKK={self.target_port}', *clang_native.get_clang_native_args(), *self.args]
113 print(cmd)
114 run_process(cmd, env=clang_native.get_clang_native_env())
115 process = Popen([os.path.abspath('server')])
116 self.processes.append(process)
117
118 # start the websocket proxy
119 print('running websockify on %d, forward to tcp %d' % (self.listen_port, self.target_port), file=sys.stderr)
120 # source_is_ipv6=True here signals to websockify that it should prefer ipv6 address when
121 # resolving host names. This matches what the node `ws` module does and means that `localhost`
122 # resolves to `::1` on IPv6 systems.
123 wsp = websockify.WebSocketProxy(verbose=True, source_is_ipv6=True, listen_host="127.0.0.1", listen_port=self.listen_port, target_host="127.0.0.1", target_port=self.target_port, run_once=True)
124 self.websockify = multiprocessing.Process(target=wsp.start_server)
125 self.websockify.start()
126 self.processes.append(self.websockify)
127 # Make sure both the actual server and the websocket proxy are running
128 for _ in range(10):
129 try:
130 if self.do_server_check:
131 server_sock = socket.create_connection(('localhost', self.target_port), timeout=1)
132 server_sock.close()
133 proxy_sock = socket.create_connection(('localhost', self.listen_port), timeout=1)
134 proxy_sock.close()
135 break
136 except OSError:
137 time.sleep(1)
138 else:
139 self.clean_processes()
140 raise Exception('[Websockify failed to start up in a timely manner]')
141
142 print('[Websockify on process %s]' % str(self.processes[-2:]))
143 return self
144
145 def __exit__(self, *args, **kwargs):
146 # try to kill the websockify proxy gracefully
147 if self.websockify.is_alive():
148 self.websockify.terminate()
149 self.websockify.join()
150

Calls

no outgoing calls