Skip to content

Commit e3bbff6

Browse files
committed
Initial
1 parent 4ff806f commit e3bbff6

File tree

4 files changed

+42
-2
lines changed

4 files changed

+42
-2
lines changed

client.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,14 +152,15 @@ def ws_start(self, use_ssl):
152152
on_error=self.ws_on_error,
153153
)
154154

155-
ssl_context = None
155+
ssl_opt = None
156156
if use_ssl: # websocket secure
157157
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
158158
ssl_context.load_verify_locations(self.m_sslfile)
159+
ssl_opt = {"context": ssl_context}
159160

160161
def run(*args):
161162
try:
162-
ws.run_forever(sslopt={"context": ssl_context})
163+
ws.run_forever(sslopt=ssl_opt)
163164
except Exception as e:
164165
ws.close()
165166
self.ws_stop_thread(ws)

test/README.TXT

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
1. Install
2+
pip install -r requirements.txt
3+
4+
2. Usage
5+
Websocket: python websocket_server.py
6+
Websocket Secure: python websocket_server.py secure

test/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
websockets

test/websocket_server.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import sys, os
2+
import pathlib
3+
import websockets, asyncio, ssl
4+
5+
import logging
6+
logger = logging.getLogger('websockets')
7+
logger.setLevel(logging.INFO)
8+
logger.addHandler(logging.StreamHandler())
9+
10+
async def handler(ws, path):
11+
try:
12+
while True:
13+
data = await ws.recv()
14+
print(f"WS Server ({ws.path}) sent '{data}'")
15+
await ws.send(data)
16+
except websockets.exceptions.ConnectionClosedOK as e:
17+
print("Client closed", e)
18+
except Exception as e:
19+
print("Exception:", e)
20+
21+
if __name__ == "__main__":
22+
# create ssl context for websocket secure
23+
ssl_context = None
24+
if len(sys.argv) == 2 and sys.argv[1].lower() == "secure":
25+
normalize_path = lambda path: path.replace("\\", "/").replace("/", os.path.sep)
26+
ssl_file_path = normalize_path(os.path.join(pathlib.Path(__file__).resolve().parent.parent, "preferences/local.pem"))
27+
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
28+
ssl_context.load_cert_chain(ssl_file_path)
29+
# start websocket server
30+
ws_server = websockets.serve(handler, "127.0.0.1", 1609, ssl=ssl_context)
31+
asyncio.get_event_loop().run_until_complete(ws_server)
32+
asyncio.get_event_loop().run_forever()

0 commit comments

Comments
 (0)