Python: Socket doesn't want to shutdown() and setsockopt() is ignored? (Problem debugging)
Edited
Original question was about trouble with reconnecting (close() and shutdown() confusion). The below code is the working code (fixed) For Googler's, this script is an IRC bot. Feature list:
- Keep reconnecting until connection available
- If assigned nick is already taken, puts string behind name (repeats until success)
- Listens to PING and responds with PONG
- Can listen to commands and respond
- If connection is lost, the bot will try to reconnect (if no information is received, no PING, in 5 mins, it treats the connection as if it was disconnected)
That is about it :)
Full Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import socket
import string
import os
import platform
import time
# Variables
HOST = "irc.server.net"
PORT = 6667
NICK = "Nickname"
IDENT = "Nickname"
REALNAME = os.getenv('USER')
CHAN = "##Channel"
readbuffer = ""
# The Connection itself
keep_connecting = True
while keep_connecting:
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1开发者_运维知识库)
irc.settimeout(300)
try:
irc.connect((HOST, PORT))
pass
except socket.gaierror:
print "No connection, attempting to connect again"
time.sleep(5)
continue
print "Sending info..."
irc.send("NICK %s\r\n" % NICK)
irc.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
irc.send("JOIN :%s\r\n" % CHAN)
# Initial msg to send when bot connects
irc.send("PRIVMSG %s :%s\r\n" % (CHAN, "TehBot: "+ NICK + " Realname: " + REALNAME + " ."))
while True:
try:
data = irc.recv(4096)
print data
# If disconneted from IRC
if len(data) == 0:
print "Length of data == 0 ?..."
break
# If Nick is in use
if data.find (NICK + " :Nickname is already in use") != -1:
NICK = NICK + str(time.time())[5:-3]
break
# Ping Pong so we don't get disconnected
if data[0:4] == "PING":
irc.send ("PONG " + data.split() [ 1 ] + "\r\n")
except socket.timeout:
print "Socket timeout!"
irc.close()
break
This is most probably because you're switching off wi-fi and the interface is removed from system so you get something like Can't assign requested address. You would get such an error while trying to bind to non-existing local address.
The other thing is you won't be able to reconnect on the same socket after calling close
as it releases all resources associated to the socket.
精彩评论