Python重用同一个套接字并遇到问题

2024-09-27 21:28:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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 /,但不适用于第二个。我该怎么解决这个问题?

Tags: 端口命令脚本localhosthttphostinputsize
2条回答

根据对@samplebias'答案的评论,我认为这与您希望实现的目标类似:

import errno
import socket

size = 1024
host = 'localhost'
port = 80


def connectsocket(userHost, userPort):

    while(1):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # TCP socket
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.connect((userHost, userPort))

        command = raw_input("Command: ")

        s.send(command + '\r\n\r\n')  # Send command
        response = s.recv(size)  # Recieve output
        print response

        try:
            s.shutdown(socket.SHUT_RDWR)
        except socket.error, exc:
            # Depending on the platform, shutting down one half of the
            # connection can also close the opposite half
            if exc.errno != errno.ENOTCONN:
                raise

        s.close()


connectsocket(host, port)

您也可以查看Twisted库。你也可以看看这本书:Foundations of Python Network Programming。在

python文档网站上还有一个很好的socket tutorial可以帮助您。最后,但并非最不重要的是,我在谷歌上找到了一个slightly more comprehensive tutorial,它对初学者来说很不错。在

好吧。在

您需要告诉服务器保持TCP连接打开,并期望更多请求:

headers = 'Connection: keep-alive\r\n'
s.send(input + '\r\n' + headers + '\r\n')

另外,请尝试指定HTTP版本:

^{pr2}$

相关问题 更多 >

    热门问题