1

我是套接字编程的新手,有人能告诉我我在这里做错了什么吗?我收到此错误。当我不调用将其定义为函数时,该程序工作正常。我从 main 调用它的那一刻是给我这个错误。有人请帮忙!

#!/usr/bin/env python
import socket
import sys
import urlparse
from urlparse import urlparse

def main(url):
  t=url
  o = urlparse(t)
  x=".".join(o.netloc.split(".")[-2:])
  head1= o.path
  host = o.netloc
  port = 80

  try:
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  except socket.error, msg:
     sys.stderr.write("[ERROR] %s\n" % msg[1])
     sys.exit()
  try:
     sock.connect((host, port))
     except socket.error, msg:
     sys.stderr.write("[ERROR] %s\n" % msg[1])
     sys.exit()
  try:
     sock.send("HEAD %s HTTP/1.0\r\n\r\n" % head1)
  except sock.error:
     sys.exit()   

  s=sock.recv(600)
  sock.shutdown()
  import sys
  sys.exit
  sock.close()
  return s

 x=main("www.google.ca")
 print x

ERROR I get:
Traceback (most recent call last):
File "C:/myserver/cgi-bin/domainsockettest.py", line 47, in <module>
x=main("www.google.ca")
File "C:/myserver/cgi-bin/domainsockettest.py", line 40, in main
s=sock.recv(600)
error: [Errno 10054] An existing connection was forcibly closed by the remote host
4

1 回答 1

1

我建议您打印出中间值,直到您确定自己在做什么。现在看来您的 URL 拆分逻辑搞砸了:

>>> o = urlparse.urlparse('www.google.ca')
>>> o.path
'www.google.ca'
>>> o.netloc
''
>>>

还:

  • 调用sys.exit()缺少括号,
  • 在那个出口之后你正试图做某事,
  • 返回关闭的套接字是完全没用的。
于 2012-12-03T13:32:06.820 回答