我使用Python编写一个简单的脚本,该脚本将使用套接字连接到主机/端口。我知道套接字只能使用一次,这就是为什么我根本不关闭套接字,但是当我连接到80端口的localhost并尝试一个简单的命令,如GET /
时,它第一次起作用,但第二次我执行GET /
或任何其他HTTP命令时,它不会打印输出。这是我所拥有的
import socket
size = 1024
host = 'localhost'
port = 80
def connectsocket(userHost, userPort):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP socket
s.connect((userHost, userPort))
while(1):
input = raw_input("Command: ")
s.send(input + '\r\n\r\n') #Send command
r = s.recv(size) #Recieve output
print(r)
connectsocket(host, port)
但我假设这是一个输出:
amartin@homebox:~$ python socketconn.py
Command: GET /
[BUNCH OF HTML CODE]
Command: GET /
Command:
如您所见,它适用于第一个GET /
,但不适用于第二个。我该怎么解决这个问题?
根据对@samplebias'答案的评论,我认为这与您希望实现的目标类似:
您也可以查看Twisted库。你也可以看看这本书:Foundations of Python Network Programming。在
python文档网站上还有一个很好的socket tutorial可以帮助您。最后,但并非最不重要的是,我在谷歌上找到了一个slightly more comprehensive tutorial,它对初学者来说很不错。在
好吧。在
您需要告诉服务器保持TCP连接打开,并期望更多请求:
另外,请尝试指定HTTP版本:
^{pr2}$相关问题 更多 >
编程相关推荐