原始问题是关于重新连接(close()和shutdown()混淆)的问题。以下代码是工作代码(已修复) 对于Googler来说,这个脚本是一个IRC机器人。功能列表:
就是这样:)
完整代码:
#!/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
答案 0 :(得分:1)
这很可能是因为您关闭了Wi-Fi并且界面已从系统中移除,因此您可以获得类似无法分配请求的地址的内容。尝试绑定到不存在的本地地址时会出现这样的错误。
另一件事是,在调用close
后,您将无法在同一个套接字上重新连接,因为它释放了与套接字关联的所有资源。