尝试连接到套接字时出错

时间:2017-09-16 21:21:35

标签: python sockets http networking

我正在学习如何使用python通过HTTP协议连接到套接字并检索URL。有人可以协助指出我可能出错的地方吗?

Python代码:

# Networking
## Connect to a Socket
import socket
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80)) # Host, Port Number

cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)

while TRUE:
    data = mysock.recv(512)
    if (len(data)<1):
        break
    print(data.decode())
mysock.close()

我在Windows 10命令提示符上运行程序:

C:\Users\Kane\Desktop>python networking.py

我收到以下错误消息:

Traceback (most recent call last):
  File "networking.py", line 7, in <module>
    mysock.connect(('data.pr4.org', 80)) # Host, Port Number
  File "C:\Users\Kane\Anaconda2\lib\socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 11001] getaddrinfo failed

感谢。

1 个答案:

答案 0 :(得分:0)

原来,@ t.m.adam是对的。

代码工作正常,但TRUE应为True。

之前可能是主机或服务器问题。如果其他人可以得到以下相同的输出,我将删除该问题:

C:\Users\Kane\Desktop>python networking.py
HTTP/1.1 200 OK
Date: Sun, 17 Sep 2017 00:12:07 GMT
Server: Apache/2.4.7 (Ubuntu)
Last-Modified: Sat, 13 May 2017 11:22:22 GMT
ETag: "1d3-54f6609240717"
Accept-Ranges: bytes
Content-Length: 467
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Connection: close
Content-Type: text/plain