source: python-simple-websocket-server/simple-websocket-server/SimpleWebSocketServer/SimpleExampleServer.py @ 1309

Last change on this file since 1309 was 1309, checked in by joamuran, 3 years ago

initial upload

File size: 2.2 KB
Line 
1'''
2The MIT License (MIT)
3Copyright (c) 2013 Dave P.
4'''
5
6import signal, sys, ssl
7from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer, SimpleSSLWebSocketServer
8from optparse import OptionParser
9
10class SimpleEcho(WebSocket):
11
12   def handleMessage(self):
13      self.sendMessage(self.data)
14
15   def handleConnected(self):
16      pass
17
18   def handleClose(self):
19      pass
20
21clients = []
22class SimpleChat(WebSocket):
23
24   def handleMessage(self):
25      for client in clients:
26         if client != self:
27            client.sendMessage(self.address[0] + u' - ' + self.data)
28
29   def handleConnected(self):
30      print (self.address, 'connected')
31      for client in clients:
32         client.sendMessage(self.address[0] + u' - connected')
33      clients.append(self)
34
35   def handleClose(self):
36      clients.remove(self)
37      print (self.address, 'closed')
38      for client in clients:
39         client.sendMessage(self.address[0] + u' - disconnected')
40
41
42if __name__ == "__main__":
43
44   parser = OptionParser(usage="usage: %prog [options]", version="%prog 1.0")
45   parser.add_option("--host", default='', type='string', action="store", dest="host", help="hostname (localhost)")
46   parser.add_option("--port", default=8000, type='int', action="store", dest="port", help="port (8000)")
47   parser.add_option("--example", default='echo', type='string', action="store", dest="example", help="echo, chat")
48   parser.add_option("--ssl", default=0, type='int', action="store", dest="ssl", help="ssl (1: on, 0: off (default))")
49   parser.add_option("--cert", default='./cert.pem', type='string', action="store", dest="cert", help="cert (./cert.pem)")
50   parser.add_option("--ver", default=ssl.PROTOCOL_TLSv1, type=int, action="store", dest="ver", help="ssl version")
51
52   (options, args) = parser.parse_args()
53
54   cls = SimpleEcho
55   if options.example == 'chat':
56      cls = SimpleChat
57
58   if options.ssl == 1:
59      server = SimpleSSLWebSocketServer(options.host, options.port, cls, options.cert, options.cert, version=options.ver)
60   else:
61      server = SimpleWebSocketServer(options.host, options.port, cls)
62
63   def close_sig_handler(signal, frame):
64      server.close()
65      sys.exit()
66
67   signal.signal(signal.SIGINT, close_sig_handler)
68
69   server.serveforever()
Note: See TracBrowser for help on using the repository browser.