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

2022-08-05 12:43:48 浏览数 (1)

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

概述

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

代码

代码语言:javascript复制
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 OKrnContent-Type:text/html; charset=utf-8rnrn")
        conn.send("<h2>测试数据</h2>".encode('utf-8'))
        # 关闭链接
        conn.close()


if __name__ == '__main__':
    main()

使用

  • 运行程序后,在浏览器访问 localhost:8000即可进入代码中的 while 循环内,收到返回并在浏览器显示
  • 同时终端收到信息打印出来:
代码语言:javascript复制
start listening!
b'GET / HTTP/1.1rnHost: localhost:8000rnConnection: keep-alivernCache-Control: max-age=0rnUpgrade-Insecure-Requests: 1rnUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36rnAccept: 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.9rnSec-Fetch-Site: nonernSec-Fetch-Mode: navigaternSec-Fetch-User: ?1rnSec-Fetch-Dest: documentrnAccept-Encoding: gzip, deflate, brrnAccept-Language: zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6rnrn'
b'GET /favicon.ico HTTP/1.1rnHost: localhost:8000rnConnection: keep-alivernPragma: no-cachernCache-Control: no-cachernUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36rnAccept: image/avif,image/webp,image/apng,image/*,*/*;q=0.8rnSec-Fetch-Site: same-originrnSec-Fetch-Mode: no-corsrnSec-Fetch-Dest: imagernReferer: http://localhost:8000/rnAccept-Encoding: gzip, deflate, brrnAccept-Language: zh,en-US;q=0.9,en;q=0.8,zh-TW;q=0.7,zh-CN;q=0.6rnrn'
b''

0 人点赞