Search code examples
pythonsocketsbotsirc

Python: socket connection still open


I've read some questions on this topic here, but i couldn't get an simple answer. I'll provide some code so it can be easier.

import socket

irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )

irc.connect((network, port))

# Do the rest of the connection (set nick, user, join chan)
# Okay, now we're connected

while True:

    doAllTheBotStuff()

I have a !quit command that breaks the while True: loop. But sometimes i get disconected for other reasons, like ping timeout, or my internet crashes. What I wanted to do is:

while True:

    doAllTheBotStuff()

    if not stillConnected():
        break 

How can i do that stillConnected() function ?


Read/Write:

I've made a class for my bot, but hopefully you can understand it without all that information

# READING 

ready = select.select([self.irc], [], [], 1)
if ready[0]:
    temp = self.irc.recv(4096)
    # Here I handle the reading. Parse commands and all that stuff.   

The writing is always a response to what is read. I use this function:

def send_irc_cmd(self, cmd, args):
    self.irc.send(cmd+" :"+args+"\r\n")

Solution

  • I think all you need to do is to add something after the line...

    temp = self.irc.recv(4096)
    

    ...that checks if temp is the empty string, which indicates the remote host has closed the connection, and use that to break out of your loop.

    I can't really be more accurate or specific because your code sample is incomplete, and/or a simplification of the actual code.