Python3:无法打印套接字Web服务器请求

发布于 2025-01-20 13:50:25 字数 1753 浏览 1 评论 0原文

我正在创建一个套接字 Web 服务器(必须不使用 httpServer),我的工作是从请求中将“index.html”打印到本地主机。我可以正常打印请求,但它不会显示在我的浏览器上。

服务器:

from socket import *
def main():
    serversocket = socket(AF_INET, SOCK_STREAM)
    try :
        serversocket.bind(('localhost',9000))
        serversocket.listen(5)
        while(1):
            clientsocket, address = serversocket.accept()

            req = clientsocket.recv(1024).decode()
            pieces = req.split("\n")
            if ( len(pieces) > 0 ) : print(pieces[0])
            #Get the content of the file
            fin = open('index.html')
            content = fin.read()
            fin.close()
            
            print(content) #This works normally

            data = "HTTP/1.1 200 OK\r\n" + content
            clientsocket.sendall(data.encode())
            clientsocket.shutdown(SHUT_WR)
    except KeyboardInterrupt :
        print("\nShut down\n")
    except Exception as exc :
        print("Error:\n")
        print(exc)

    serversocket.close()

if __name__ == "__main__":
    main()

如果我只是执行data += "Hello World\r\n\r\n",它就可以正常工作。我也尝试过更改 html 文件中的某些格式,但没有成功。

客户端:

import socket

clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSock.connect(('127.0.0.1', 9000))
cmd = 'GET http://127.0.0.1/index.html HTTP/1.1\r\n\r\n'.encode()
clientSock.send(cmd)

while True:
    data = clientSock.recv(1024)
    if len(data) < 1:
        break
    print(data.decode(),end='')

clientSock.close()

这是“index.html”,以防万一。

<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <p>Hello world!</p>
</body>
</html>

I am creating a socket web server (without using httpServer is must), my job is to print out an 'index.html' to the localhost from the request. I could print the request normally, but it won't be shown on my browser.

Server:

from socket import *
def main():
    serversocket = socket(AF_INET, SOCK_STREAM)
    try :
        serversocket.bind(('localhost',9000))
        serversocket.listen(5)
        while(1):
            clientsocket, address = serversocket.accept()

            req = clientsocket.recv(1024).decode()
            pieces = req.split("\n")
            if ( len(pieces) > 0 ) : print(pieces[0])
            #Get the content of the file
            fin = open('index.html')
            content = fin.read()
            fin.close()
            
            print(content) #This works normally

            data = "HTTP/1.1 200 OK\r\n" + content
            clientsocket.sendall(data.encode())
            clientsocket.shutdown(SHUT_WR)
    except KeyboardInterrupt :
        print("\nShut down\n")
    except Exception as exc :
        print("Error:\n")
        print(exc)

    serversocket.close()

if __name__ == "__main__":
    main()

if I just do data += "<html><body>Hello World</body></html>\r\n\r\n", it works normally. I have also tried to change some formats in html file but it didn't work.

Client:

import socket

clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSock.connect(('127.0.0.1', 9000))
cmd = 'GET http://127.0.0.1/index.html HTTP/1.1\r\n\r\n'.encode()
clientSock.send(cmd)

while True:
    data = clientSock.recv(1024)
    if len(data) < 1:
        break
    print(data.decode(),end='')

clientSock.close()

This is the 'index.html' just in case.

<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <p>Hello world!</p>
</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城花音 2025-01-27 13:50:25

我认为你必须缓冲服务器响应,因为如果数据不适合一个卡盘,你就无法读取整个页面。

你可以这样做:

# retrieve server response
chunk = skt.recv(4096)
if chunk:
    buffer = b''  // data sent in bytes on the socket
    while True:
        buffer += chunk
        if buffer.find(CONTROL_FLAG) > 0:
            buffer = buffer.replace(CONTROL_FLAG, b'')
            break
        chunk = skt.recv(4096)

在我的例子中,我使用了一个字符串标志(CONTROL_FLAG)来知道响应的结尾。我希望这个想法能够对你有所帮助。

I think that you have to bufferize the server response because if the data doesn't fit in one chuck you cannot read the whole page.

You can do something like that:

# retrieve server response
chunk = skt.recv(4096)
if chunk:
    buffer = b''  // data sent in bytes on the socket
    while True:
        buffer += chunk
        if buffer.find(CONTROL_FLAG) > 0:
            buffer = buffer.replace(CONTROL_FLAG, b'')
            break
        chunk = skt.recv(4096)

In my case I used a string flag (CONTROL_FLAG) to know the end of the response. I hope this idea can be of help to you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文