Python:Socket不想关闭()和setsockopt()被忽略? (问题调试)

时间:2011-07-31 17:01:21

标签: python sockets

被修改

原始问题是关于重新连接(close()和shutdown()混淆)的问题。以下代码是工作代码(已修复) 对于Googler来说,这个脚本是一个IRC机器人。功能列表:

  • 保持重新连接,直到连接可用
  • 如果已经指定了分配,则将字符串放在名称后面(重复直到成功)
  • 收听PING并以PONG回复
  • 可以收听命令并回复
  • 如果连接丢失,机器人将尝试重新连接(如果没有收到任何信息,没有PING,在5分钟内,它会将连接视为已断开连接)

就是这样:)

完整代码:

#!/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

1 个答案:

答案 0 :(得分:1)

这很可能是因为您关闭了Wi-Fi并且界面已从系统中移除,因此您可以获得类似无法分配请求的地址的内容。尝试绑定到不存在的本地地址时会出现这样的错误。

另一件事是,在调用close后,您将无法在同一个套接字上重新连接,因为它释放了与套接字关联的所有资源。