forked from SevenW/httpwebsockethandler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExampleWSServer.py
More file actions
67 lines (58 loc) · 2.04 KB
/
ExampleWSServer.py
File metadata and controls
67 lines (58 loc) · 2.04 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
60
61
62
63
64
65
66
67
#main program and imports for standalone purpose
import sys
import threading
import ssl
from base64 import b64encode
VER = sys.version_info[0]
if VER >= 3:
from socketserver import ThreadingMixIn
from http.server import HTTPServer
from io import StringIO
else:
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer
from StringIO import StringIO
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(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.encode("ascii"))
if secure:
server.auth = b64encode(credentials.encode("ascii"))
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()