Skip to content

Commit c73c987

Browse files
committed
Properly detect read error on socket (closes #1)
1 parent 77215c3 commit c73c987

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

weercd.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,15 @@ def __init__(self, sock, addr, args):
155155
self.nick_number = 0
156156
self.channels = {}
157157
self.quit = False
158+
self.read_error = False
158159
self.end_msg = ""
159160
self.end_exception = None
160161
self.connect()
161162

163+
def has_ended(self):
164+
"""Check if the server has ended or the client has disconnected."""
165+
return self.quit or self.read_error
166+
162167
def random_nick(self, with_number=False):
163168
"""Return a random nick name."""
164169
if with_number:
@@ -216,7 +221,12 @@ def parse_message(self, message):
216221

217222
def recv(self, timeout):
218223
"""Receive messages and parse them."""
219-
msgs = self.conn.read(timeout)
224+
try:
225+
msgs = self.conn.read(timeout)
226+
except Exception as exc:
227+
print(f"Error reading on socket: {exc}")
228+
self.read_error = True
229+
return
220230
for msg in msgs:
221231
self.parse_message(msg)
222232

@@ -225,6 +235,8 @@ def connect(self):
225235
count = self.args.nickused
226236
while self.nick == "":
227237
self.recv(0.1)
238+
if self.has_ended():
239+
return
228240
if self.nick and count > 0:
229241
self.send_command(
230242
"433",
@@ -422,7 +434,7 @@ def send_file(self): # pylint: disable=too-many-branches
422434

423435
def run(self):
424436
"""Execute the action asked for the client."""
425-
if self.quit:
437+
if self.has_ended():
426438
return
427439

428440
# send commands from file (which can be stdin)
@@ -440,14 +452,19 @@ def run(self):
440452
sys.stdout.flush()
441453
with time_limit(self.args.time):
442454
try:
443-
while not self.quit:
455+
while not self.has_ended():
444456
self.flood()
445457
except KeyboardInterrupt:
446458
self.end_msg = "interrupted"
447459
except TimeoutException:
448460
self.end_msg = "timeout"
449461
except Exception as exc: # pylint: disable=broad-except
450-
self.end_msg = "quit received" if self.quit else "connection lost"
462+
if self.quit:
463+
self.end_msg = "quit received"
464+
elif self.read_error:
465+
self.end_msg = "read error"
466+
else:
467+
self.end_msg = "connection lost"
451468
self.end_exception = exc
452469

453470
def end(self):

0 commit comments

Comments
 (0)