Repository navigation
Expand file tree
/
Copy pathExampleWSServer.py
More file actions
executable file
·59 lines (52 loc) · 1.87 KB
/
Copy pathExampleWSServer.py
File metadata and controls
executable file
·59 lines (52 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#main program and imports for standalone purpose
import sys
import threading
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import ssl
from base64 import b64encode
from HTTPWebSocketsHandler import HTTPWebSocketsHandler
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8000
if len(sys.argv) > 2:
secure = str(sys.argv[2]).lower()=="secure"
else:
secure = False
if len(sys.argv) > 3:
credentials = str(sys.argv[3])
else:
credentials = ""
class WSSimpleEcho(HTTPWebSocketsHandler):
def on_ws_message(self, message):
if message is None:
message = ''
# echo message back to client
self.send_message(str(message))
self.log_message('websocket received "%s"',str(message))
def on_ws_connected(self):
self.log_message('%s','websocket connected')
def on_ws_closed(self):
self.log_message('%s','websocket closed')
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
def _ws_main():
try:
#Replace WSSimpleEcho with your own subclass of HTTPWebSocketHandler
server = ThreadedHTTPServer(('', port), WSSimpleEcho)
server.daemon_threads = True
server.auth = b64encode(credentials)
if secure:
server.auth = b64encode(credentials)
server.socket = ssl.wrap_socket (server.socket, certfile='./server.pem', server_side=True)
print('started secure https server at port %d' % (port,))
else:
print('started http server at port %d' % (port,))
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
server.socket.close()
if __name__ == '__main__':
_ws_main()