使用 Python Socket 包搭建简易服务器

本文最后更新于:2021年12月11日 上午

本文记录使用Python Socket包搭建简易服务器的代码。

概述

平时访问网站底层大多是socket封装的http请求,都是基于tcp-ip协议进行通信的;角色分为服务器端和客户端。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import socket

def main():
# ipv4 # tcp-ip
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 监听本机 8000 端口
sock.bind(('localhost', 8000))
# 最多同时5个链接
sock.listen(5)

print('start listening! ')
while True:
# 接受请求
conn, addr = sock.accept()
# 获取数据
data = conn.recv(1024)
print(data)
# 返回网页显示内容
conn.send(b"HTTP/1.1 200 OK\r\nContent-Type:text/html; charset=utf-8\r\n\r\n")
conn.send("<h2>测试数据</h2>".encode('utf-8'))
# 关闭链接
conn.close()


if __name__ == '__main__':
main()

使用

  • 运行程序后,在浏览器访问 localhost:8000即可进入代码中的 while 循环内,收到返回并在浏览器显示

  • 同时终端收到信息打印出来:
1
2
3
4
start listening!
b'GET / HTTP/1.1\r\nHost: localhost:8000\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\r\nSec-Fetch-Site: none\r\nSec-Fetch-Mode: navigate\r\nSec-Fetch-User: ?1\r\nSec-Fetch-Dest: document\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6\r\n\r\n'
b'GET /favicon.ico HTTP/1.1\r\nHost: localhost:8000\r\nConnection: keep-alive\r\nPragma: no-cache\r\nCache-Control: no-cache\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36\r\nAccept: image/avif,image/webp,image/apng,image/*,*/*;q=0.8\r\nSec-Fetch-Site: same-origin\r\nSec-Fetch-Mode: no-cors\r\nSec-Fetch-Dest: image\r\nReferer: http://localhost:8000/\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6\r\n\r\n'
b''