Skip to content

Commit

Permalink
Properly clean up closed connections (Fixes #19)
Browse files Browse the repository at this point in the history
  • Loading branch information
innuos-ccarvalho authored and miguelgrinberg committed Nov 16, 2022
1 parent 59b6694 commit 9bda310
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/simple_websocket/ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,9 @@ def __init__(self, sock=None, connection_type=None, receive_bytes=4096,
import threading
event_class = threading.Event
if selector_class is None:
import selectors
selector_class = selectors.DefaultSelector

self.selector_class = selector_class
self.event = event_class()
self.selector = selector_class()

self.ws = WSConnection(connection_type)
self.handshake()
Expand Down Expand Up @@ -100,7 +98,7 @@ def receive(self, timeout=None):
"""Receive data over the WebSocket connection.
:param timeout: Amount of time to wait for the data, in seconds. Set
to ``None`` (the default) to wait undefinitely. Set
to ``None`` (the default) to wait indefinitely. Set
to 0 to read without blocking.
The data received is returned, as ``bytes`` or ``str``, depending on
Expand All @@ -118,7 +116,7 @@ def close(self, reason=None, message=None):
"""Close the WebSocket connection.
:param reason: A numeric status code indicating the reason of the
closure, as defined by the WebSocket specifiation. The
closure, as defined by the WebSocket specification. The
default is 1000 (normal closure).
:param message: A text message to be sent to the other side.
"""
Expand All @@ -142,7 +140,7 @@ def _thread(self):
sel = None
if self.ping_interval:
next_ping = time() + self.ping_interval
sel = self.selector
sel = self.selector_class()
sel.register(self.sock, selectors.EVENT_READ, True)

while self.connected:
Expand All @@ -166,8 +164,11 @@ def _thread(self):
self.connected = False
self.event.set()
break

self.ws.receive_data(in_data)
self.connected = self._handle_events()
sel.close() if sel else None
self.sock.close()

def _handle_events(self):
keep_going = True
Expand Down

0 comments on commit 9bda310

Please sign in to comment.