首先看一下效果
完整代码
import socket
from multiprocessing import ProcessHTML_ROOT_DIR = ""def handle_client(client_socket):request_data = client_socket.recv(1024)print("request data:", request_data)response_start_line = "HTTP/1.0 200 OK\r\n"response_headers = "Server: My server\r\n"response_body = "hello world"response = response_start_line + \"\r\n" + response_bodyprint("response data:", response)client_socket.send(bytes(response, "utf-8"))client_socket.close()if __name__ == "__main__":server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server_socket.bind(("127.0.0.1", 8080))server_socket.listen(128)while True:client_socket, client_address = server_socket.accept()handle_client_process = Process(target=handle_client, args=(client_socket,))handle_client_process.start()client_socket.close()
文章目录
- 首先看一下效果
- 完整代码
- 服务器
- socket
- bind
- listen
- accept
- 多进程处理任务
服务器
socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
AF_INET指定使用IPv4协议,如果要用更先进的IPv6,就指定为AF_INET6。SOCK_STREAM指定使用面向流的TCP协议,这样,一个Socket对象就创建成功,但是还没有建立连接。
bind
server_socket.bind(("127.0.0.1", 8080))
服务器可能有多块网卡,可以绑定到某一块网卡的IP地址上,也可以用0.0.0.0绑定到所有的网络地址,还可以用127.0.0.1绑定到本机地址。127.0.0.1是一个特殊的IP地址,表示本机地址,如果绑定到这个地址,客户端必须同时在本机运行才能连接,也就是说,外部的计算机无法连接进来。
listen
server_socket.listen(128)
调用listen()方法开始监听端口,传入的参数指定等待连接的最大数量
accept
等待并返回一个客户端的连接,采用多进程来处理要做的事情
while True:client_socket, client_address = server_socket.accept()handle_client_process = Process(target=handle_client, args=(client_socket,))handle_client_process.start()client_socket.close()
多进程处理任务
def handle_client(client_socket):request_data = client_socket.recv(1024)print("request data:", request_data)response_start_line = "HTTP/1.0 200 OK\r\n"response_headers = "Server: My server\r\n"response_body = "hello world"response = response_start_line + "\r\n" + response_bodyprint("response data:", response)client_socket.send(bytes(response, "utf-8"))client_socket.close()