Pārlūkot izejas kodu

Added missing close() method, typing bugfix, removed debug code

Taddeus Kroes 12 gadi atpakaļ
vecāks
revīzija
92410324ff
3 mainītis faili ar 11 papildinājumiem un 7 dzēšanām
  1. 6 3
      connection.py
  2. 2 2
      frame.py
  3. 3 2
      websocket.py

+ 6 - 3
connection.py

@@ -105,7 +105,6 @@ class Connection(object):
                 self.onmessage(self.receive())
             except SocketClosed as e:
                 self.close()
-                #self.onclose(e.code, e.reason)
                 break
             except Exception as e:
                 self.onerror(e)
@@ -124,7 +123,11 @@ class Connection(object):
         Close the socket by sending a CLOSE frame and waiting for a response
         close message, unless such a message has already been received earlier
         (prior to calling this function, for example). The onclose() handler is
-        called after the response has been received.
+        called after the response has been received, but before the socket is
+        actually closed. This order was chosen to prevent errors in
+        stringification in the onclose() handler. For example,
+        socket.getpeername() raises a Bad file descriptor error then the socket
+        is closed.
         """
         # Send CLOSE frame
         payload = '' if code is None else struct.pack('!H', code) + reason
@@ -145,8 +148,8 @@ class Connection(object):
             # CLOSE frame is received, so that a fragmented chain may arrive
             # fully first
 
-        self.sock.close()
         self.onclose(code, reason)
+        self.sock.close()
 
     def onopen(self):
         """

+ 2 - 2
frame.py

@@ -177,8 +177,8 @@ class ControlFrame(Frame):
         is given, the code is None and the reason is an empty string.
         """
         if self.payload:
-            code = struct.unpack('!H', self.payload[:2])
-            reason = self.payload[2:]
+            code = struct.unpack('!H', str(self.payload[:2]))
+            reason = str(self.payload[2:])
         else:
             code = None
             reason = ''

+ 3 - 2
websocket.py

@@ -81,7 +81,6 @@ class websocket(object):
         Send a number of frames.
         """
         for frame in args:
-            print 'send frame:', frame, 'to %s:%d' % self.sock.getpeername(), frame.payload
             self.sock.sendall(frame.pack())
 
     def recv(self):
@@ -90,7 +89,6 @@ class websocket(object):
         frame.
         """
         frame = receive_frame(self.sock)
-        print 'receive frame:', frame, 'from %s:%d' % self.sock.getpeername()
         return frame
 
     def recvn(self, n):
@@ -112,6 +110,9 @@ class websocket(object):
     def getsockopt(self, level, optname):
         return self.sock.getsockopt(level, optname)
 
+    def close(self):
+        self.sock.close()
+
     def server_handshake(self):
         """
         Execute a handshake as the server end point of the socket. If the HTTP