Web Server是基于Socket编程,又称之为网络编程,socket是网络编程接口,socket可以建立网络连接,读数据,写数据。socket模块定义了一些常量参数,用来指定socket的的地址族、socket的类型、以及支持的TCP/IP协议。
有一篇写的比较详细的关于HTTP协议请求过程和socket的文章,链接:http://www.admin10000.com/document/9347.html
简单实例测试socket, 代码如下:
from socket import socket, AF_INET, SOCK_STREAM
from threading import Thread port = 50008
host = 'localhost' def server():
# 建立tcp连接
sock = socket(AF_INET, SOCK_STREAM)
# 绑定本机和端口
sock.bind(('', port))
# 监听,允许连接的客户数量
sock.listen(5)
while True:
# 等待客户端连接
conn, addr = sock.accept()
# 读取客户端请求的字节数据
data = conn.recv(1024)
# 响应请求给客户端
reply = 'server got [%s]' % data
conn.send(reply.encode()) def client(name):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
sock.send(name.encode())
reply = sock.recv(1024)
sock.close()
print('client got [%s]' % reply) if __name__ == '__main__':
sthread = Thread(target=server)
sthread.daemon = True
sthread.start()
for i in range(5):
Thread(target=client, args=('client%s' % i, )).start()
运行结果如下:
client got [b"server got [b'client0']"]
client got [b"server got [b'client1']"]
client got [b"server got [b'client2']"]
client got [b"server got [b'client3']"]
client got [b"server got [b'client4']"]