【问题标题】:Python: Won't Connect to ServerPython:不会连接到服务器
【发布时间】:2011-01-24 19:56:48
【问题描述】:

我无法连接到它会打印出来的服务器

“正在连接端口...”然后它只会说“套接字超时”。

我的计划明天就要到期了,如果能实际运行就太好了。

编辑代码:现在它只会使用连接到端口.... 没有打印任何其他内容。

import socket, string, time, random, re, urllib2, cookielib, smtplib, os

class Pibot: #main class
        def __init__(self):  #basic information to allow for the rest of the program to work.
            self.server= 'irc.evilzone.org'
            self.port = 6667
            self.botname= 'pibot'
            self.chan= 'test'
            self.owner = 'Josh.H'
            self.nick = "bawt"
            self.irc = None
            self.data = ''

    def iConnect(self): #trys to connect to the server and allows the user to see if it failed to connect.
            print ("Connecting to ports...")
            print self.data
            time.sleep(3)
            try:
                    self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    self.irc.connect((self.server, self.port))

            except (socket.error, socket.herror, socket.gaierror):
                    print "Failed to connect to Ports"



    def iStart(self):
            #Not guaranteed to send all your data, iisn't checking the return values
            #however this function iStart is used to send the NICK of the bot and the USER to the server through particle data
            #it then auto joins the channel
            #in future development I'd like to get accuainted with Twisted or IRCutils as they allow it to be quiet powerful and less buggy

            self.irc.send('NICK %s\r\n' % self.nick)
            self.irc.send("USER %s %s bla :%s\r\n" % ("Ohlook", 'itsnotmy', 'Realname'))
            time.sleep(4)
            self.irc.send("JOIN #%s\r\n" % self.chan)
            self.data = self.irc.recv( 4096 ) 

    def MainLoop(self,iParse = 0): #MainLoop is used to make the commands executable ie !google !say etc;
            try:
                while True:
                    # This method sends a ping to the server and if it pings it will send a pong back
                    #in other clients they keep receiving till they have a complete line however mine does not as of right now
                    #The PING command is used to test the presence of an active client or
                    #server at the other end of the connection.  Servers send a PING
                    #message at regular intervals if no other activity detected coming
                    #from a connection.  If a connection fails to respond to a PING
                    #message within a set amount of time, that connection is closed. A
                    #PING message MAY be sent even if the connection is active.
                    #PONG message is a reply to PING message.  If parameter <server2> is
                    #given, this message will be forwarded to given target.  The <server>
                    #parameter is the name of the entity who has responded to PING message
                    #and generated this message.

                    self.data = self.irc.recv( 4096 )
                    if self.data.find ( 'PING' ) != -1:
                        self.irc.send(( "PONG %s \r\n" ) % (self.recv.split() [ 1 ])) #Possible overflow problem

                    if self.data.find( "!google" ) != -1:
                        #googles the search term and displays the first 5 results
                        #format = !google: <Search Term>
                        #One thing that I noticed is that it will print on a seperate line without the header
                        #In the next Update I would have fixed this.
                        fin = data.split(':')
                        if not fin:
                                irc.send("PRIVMSG #%s :syntax'^google :search term\r\n'" % chan)

                        else:
                            #In the next version to avoid overflow I will create another if statement and edit the search code
                            #However I am using what xgoogle has reccomended.
                                fin = fin[3].strip() 
                                gs = GoogleSearch(fin)
                                gs.results_per_page = 5
                                results = gs.get_results()
                                for result in results:
                                    irc.send("PRIVMSG #%s :%s\r\n" % (chan, result.url.encode("utf8")))

                    ###############################################################################################################################
                    #   No excpetion checking here, these functions can and will fail in time and in later versions will need to be edited.          
                    #   If hellboundhackers changes this code may break
                    #   This function takes a quote from the header of hellboundhackers
                    #   it first looks at the header of the USer agent then the header of the website (HBH) and reads it then prints
                    #   the quote when QUOTEM is recognized in the irc closes the connection to the wbesite and deletes the cookie
                    ###############################################################################################################################

                    if "QUOTEM" in self.data:
                        #Pulls a quote from HBH
                        cj = cookielib.CookieJar()
                        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
                        opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
                        opener.addheaders.append( ('Referer', 'http://www.hellboundhackers.org/index.php') )
                        resp = opener.open('http://www.hellboundhackers.org/index.php')
                        r = resp.read()
                        resp.close()
                        del cj, opener
                        da = re.findall("Enter; width:70%;'>(.*)",r)
                        self.irc.send("PRIVMSG #%s :%s\r\n" % (chan, da[0])) # Note Possible overflow

                    if "!whoareyou" in self.data:
                        #bot info allows users on IRC to see which commands are currently working
                        self.irc.send("PRIVMSG #%s :I am %s, I was created By:%s \r\n" % (self.chan, self.nick,self.owner))
                        self.irc.send("PRIVMSG #%s :I was written in Python 27, and edited with IDLE\r\n" % self.chan)
                        self.irc.send("PRIVMSG #%s :The Classes used are socket, string, time, re, urllib2, cookielib\r\n" % self.chan)
                        self.irc.send("PRIVMSG #%s :As well as some functions from various other sources(supybot,twisted,xgoogle)\r\n" % self.chan)
                        self.irc.send("PRIVMSG #%s :type ^commands for a list of things I can do\r\n" % self.chan)
            except (socket.error, socket.timeout):
                    print "Sockets timed out."

bot = Pibot()
bot.iConnect()
bot.MainLoop()

旁注:不存在错误。 非常感激。另外我只是在学习,所以不要喷我。 :(

EDIT2:我已经解决了大部分问题,现在出现错误:

Traceback (most recent call last):
  File "L:\txtbot.py", line 119, in <module>
    bot.MainLoop()
  File "L:\txtbot.py", line 64, in MainLoop
    self.irc.send(( "PONG %s \r\n" ) % (self.recv.split() [ 1 ])) #Possible overflow problem
AttributeError: Pibot instance has no attribute 'recv'

【问题讨论】:

  • 你可以使用telnet irc.evilzone.org 6667从命令行连接吗?
  • 你的意思是在代码中使用 telnet 功能还是只是一般的服务器。

标签: python networking irc


【解决方案1】:

您似乎从未将连接信息传递给套接字:

                self.irc = socket.socket()

我觉得应该是这样的:

                self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.irc.connect((self.server, self.port))

【讨论】:

  • 我最初有,但 socket.socket 是一样的(好吧,我在许多 irc 骨架中看到了类似的东西。编辑:好的,我修复了它,但现在我得到了 File "L:\txtbot .py”,第 118 行,在 bot.iConnect() 文件“L:\txtbot.py”,第 24 行,在 iConnect elf.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) NameError: global名称“elf”未定义我知道一个是因为它的自我,但另一个?
  • @21days:你能把它放在问题中或其他可以远程读取的地方,并更改你所做的代码:)
  • 您输入的是“elf”而不是“self”。 “另一个”是什么意思?那里只有一条错误消息。
  • 好的,我修复了,让我发布新编辑的代码。它仍然没有连接。
【解决方案2】:

在iConnect 中,您只是创建了一个套接字,而不是将其连接到服务器。您需要使用socket.create_connection。 此外,将 socket.error 和 socket.timeout 混为一谈不是一个好主意,因为它可能会在调试时产生误导。此外,您应该打印错误,而不仅仅是一般消息。它将帮助您找出问题所在。

【讨论】:

  • 什么意思,我要在哪里创建连接?
  • socket.socket() 只是创建一个套接字,但它没有连接它。 socket.create_connection() 创建一个套接字并连接到服务器。查一下。
  • self.irc = socket.create_connection((self.server, self.port)) 仍然没有解决问题。
  • 你应该在self.irc.connect之后添加一个print "Connected",这样你就可以看到它是否连接了。
  • 是的,我已经这样做了,等等;现在得到:文件“L:\txtbot.py”,第 117 行,在 bot.iConnect() 文件“L:\txtbot.py”,第 25 行,在 iConnect self.server = socket.create_connection( ((self.server,self.port, 0, socket.SOCK_STREAM))) 文件“C:\Python27\lib\socket.py”,第 551 行,在 create_connection 主机中,端口 = 地址 ValueError:解压的值太多我'很抱歉这只是需要完成......
【解决方案3】:

你不会在任何地方打电话给iStart。如果我没记错我的 IRC,您需要先发送您的昵称信息,然后它才会将任何数据发回给您。

【讨论】:

  • bot = Pibot() bot.iConnect() bot.iStart() bot.MainLoop()
  • 是的,我很抱歉,但现在我遇到问题的代码似乎是 Traceback(最近一次调用最后一次):文件“L:\txtbot.py”,第 119 行, 在 bot.MainLoop() 文件 "L:\txtbot.py", 第 64 行, 在 MainLoop self.irc.send(( "PONG %s \r\n" ) % (self.recv.split( ) [ 1 ])) #可能的溢出问题 AttributeError: Pibot instance has no attribute 'recv'
  • self 是你的班级。 self.irc 是实际的套接字。您的代码中有多个地方缺少self 或缺少irc。
  • 呃……你到底是什么意思。
  • 检查具有irc 的每一行以确保self 在它之前。还要检查self.irc 是否在任何具有send 或recv 的内容之前。我在您的 MainLoop 函数中发现了大约 2 或 3 个。
猜你喜欢
  • 2012-07-13
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 2014-10-06
  • 2019-12-19
  • 1970-01-01
相关资源
最近更新 更多