Http 请求和响应不起作用

Http 请求和响应不起作用

我正在尝试使用简单的 Socket 进行 Http 连接,但无法发送任何请求或获取任何响应。

#!/usr/bin/env python3

"""
 Implements a simple HTTP/1.0 Server

"""

import socket


# Define socket host and port
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 8000

# Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
print('Listening on port %s ...' % SERVER_PORT)

while True:
    # Wait for client connections
    client_connection, client_address = server_socket.accept()

    # Get the client request
    request = client_connection.recv(1024).decode()
    print(request)

    # Send HTTP response
    response = 'HTTP/1.0 200 OK\n\nHello World'
    client_connection.sendall(response.encode())
    client_connection.close()

# Close socket
server_socket.close()

上述代码的结果是

btssim@ni12-926:~/Testing$ python test_server.py
Listening on port 8000 ...

cat /etc/hosts 的结果是

127.0.0.1       localhost
10.68.196.88    NI12-926
#IP6#   NI12-9266

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

相关内容