Permalink
Browse files

Going to Python 3.1. Adding some comments.

  • Loading branch information...
1 parent 2a1d0d7 commit b43e8a5ab37689451c3f9fa2a6e2767b0690c9a2 @adngdb committed Jul 22, 2010
Showing with 33 additions and 14 deletions.
  1. +1 −0 server.py
  2. +7 −7 websocketclient.py
  3. +25 −7 websocketserver.py
View
@@ -2,4 +2,5 @@
import websocketserver
+# Launch the server
websocketserver.WebSocketServer().start()
View
@@ -17,14 +17,14 @@ def __init__(self, sock, addr, server):
def run(self):
# Handshaking, create the WebSocket connection
handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nWebSocket-Origin: http://%s\r\nWebSocket-Location: ws://%s/\r\nWebSocket-Protocol: sample\r\n\r\n" % (config.httphost, config.sockethost)
- self.s.send(handshake)
+ self.s.send(handshake.encode())
data = self.s.recv(1024)
# Receive and handle data
while 1:
data = self.s.recv(1024)
if not data: break
- print 'Data from', self.addr, ':', data
+ print('Data from', self.addr, ':', data)
self.onreceive(data)
# Close the client connection
@@ -34,15 +34,15 @@ def close(self):
"""
Close this connection
"""
- print 'Client closed: ', self.addr
- self.server.remove(self.s)
+ print('Client closed: ', self.addr)
+ self.server.remove(self)
self.s.close()
def send(self, msg):
"""
Send a message to this client
"""
- msg = '\x00' + msg + '\xff'
+ msg = b'\x00' + msg + b'\xff'
self.s.send(msg)
def onreceive(self, data):
@@ -59,6 +59,6 @@ def _clean(self, msg):
"""
Remove special chars used for the transmission
"""
- msg = msg.replace('\x00', '', 1)
- msg = msg.replace('\xff', '', 1)
+ msg = msg.replace(b'\x00', b'', 1)
+ msg = msg.replace(b'\xff', b'', 1)
return msg
View
@@ -6,25 +6,43 @@
import websocketclient
class WebSocketServer:
+ """
+ Handle the Server, bind and accept new connections, open and close
+ clients connections.
+ """
def __init__(self):
self.clients = []
def start(self):
+ """
+ Start the server.
+ """
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', config.socketport))
s.listen(1)
- while 1:
- conn, addr = s.accept()
- print 'Connected by', addr
- self.clients.append(conn)
- websocketclient.WebSocketClient(conn, addr, self).start()
+
+ try:
+ while 1:
+ conn, addr = s.accept()
+ print('Connected by', addr)
+ newClient = websocketclient.WebSocketClient(conn, addr, self)
+ self.clients.append(newClient)
+ newClient.start()
+ except KeyboardInterrupt:
+ [client.close() for client in self.clients]
+ s.close()
def send_all(self, data):
- data = '\x00' + data + '\xff'
- [conn.send(data) for conn in self.clients]
+ """
+ Send a message to all the currenly connected clients.
+ """
+ [client.send(data) for client in self.clients]
def remove(self, client):
+ """
+ Remove a client from the connected list.
+ """
l = threading.Lock()
l.acquire()
self.clients.remove(client)

0 comments on commit b43e8a5

Please sign in to comment.