forked from dpallot/simple-websocket-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleExampleServer.py
71 lines (53 loc) · 2.22 KB
/
SimpleExampleServer.py
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
68
69
70
71
'''
The MIT License (MIT)
Copyright (c) 2013 Dave P.
'''
import signal
import sys
import ssl
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer, SimpleSSLWebSocketServer
from optparse import OptionParser
class SimpleEcho(WebSocket):
def handleMessage(self):
self.sendMessage(self.data)
def handleConnected(self):
pass
def handleClose(self):
pass
clients = []
class SimpleChat(WebSocket):
def handleMessage(self):
for client in clients:
if client != self:
client.sendMessage(self.address[0] + u' - ' + self.data)
def handleConnected(self):
print (self.address, 'connected')
for client in clients:
client.sendMessage(self.address[0] + u' - connected')
clients.append(self)
def handleClose(self):
clients.remove(self)
print (self.address, 'closed')
for client in clients:
client.sendMessage(self.address[0] + u' - disconnected')
if __name__ == "__main__":
parser = OptionParser(usage="usage: %prog [options]", version="%prog 1.0")
parser.add_option("--host", default='', type='string', action="store", dest="host", help="hostname (localhost)")
parser.add_option("--port", default=8000, type='int', action="store", dest="port", help="port (8000)")
parser.add_option("--example", default='echo', type='string', action="store", dest="example", help="echo, chat")
parser.add_option("--ssl", default=0, type='int', action="store", dest="ssl", help="ssl (1: on, 0: off (default))")
parser.add_option("--cert", default='./cert.pem', type='string', action="store", dest="cert", help="cert (./cert.pem)")
parser.add_option("--ver", default=ssl.PROTOCOL_TLSv1, type=int, action="store", dest="ver", help="ssl version")
(options, args) = parser.parse_args()
cls = SimpleEcho
if options.example == 'chat':
cls = SimpleChat
if options.ssl == 1:
server = SimpleSSLWebSocketServer(options.host, options.port, cls, options.cert, options.cert, version=options.ver)
else:
server = SimpleWebSocketServer(options.host, options.port, cls)
def close_sig_handler(signal, frame):
server.close()
sys.exit()
signal.signal(signal.SIGINT, close_sig_handler)
server.serveforever()