1. #!/usr/bin/env/ python 2. # -*- coding:utf-8 -*- 3. 4. import traceback 5. import socket 6. import errno 7. import threading 8. 9. END_TAG_F = b'nn' 10. END_TAG_S = b'nrn' 11. 12. # 设置web server响应内容 13. html_content = '<html><h1>这是线程({})的页面 <h1></html>' 14. 15. # 设置响应headers 16. resp_args = ['HTTP/1.0 200 OK', 'Date: Sun, 22 nov 2020 19:00:00 GMT', 17. 'Content-Type: text/html;charset=utf-8', 18. 'Content-Length: {}rn'] 19. 20. 21. def connet_operate(conn, addr): 22. """ 23. 请求操作 24. :param conn: 25. :param addr: 26. :return: 27. """ 28. request = b'' 29. while END_TAG_F not in request and END_TAG_S not in request: 30. request += conn.recv(1024) 31. 32. print("请求内容: ", request) 33. c = threading.current_thread() 34. _ = html_content.format(c.name) 35. resp_args.Append(_) 36. content_length = len(_.encode()) 37. _resp = "rn".join(resp_args) 38. 39. _resp = _resp.format(content_length) 40. conn.send(_resp.encode()) 41. conn.close() 42. 43. 44. def web_server(): 45. # socket.AF_INET用于服务器与服务器之间同行 46. # socket.SOCK_STREAM用于基于TCP流的通信 47. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 48. server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 49. # 监听本地8888端口 50. server.bind(('127.0.0.1', 8888)) 51. server.listen() 52. print("web server已经启动") 53. 54. try: 55. n = 0 56. while True: 57. try: 58. conn, address = server.accept() 59. except socket.error as e: 60. if e.args[0] != errno.EAGAIN: 61. raise Exception(e) 62. continue 63. 64. n += 1 65. # 通过threading实现web server多线程 66. t = threading.Thread(target=connet_operate, args=(conn, address), name='thread{}'.format(n)) 67. t.start() 68. except Exception as e: 69. print(traceback.format_exc(e)) 70. server.close() 71. 72. if __name__ == "__main__": 73. web_server()
推荐阅读
- Web端非常有用的一个文件上传插件——FilePond
- 想了解蓝牙音源解码必看文章 | SBC、AAC、aptX、LDAC 秒懂
- web交换机管理怎么管理?两种方法,轻松掌握
- webpack教程:如何从头开始设置 webpack 5
- 一文看懂USB和雷电接口规范的发展史
- 一文看懂微服务架构之注册中心Consul、Nacos
- 快速优化 Web 性能的10 个手段
- 10个对web开发人员有用的HTML文件上传技巧
- web应用防火墙是做什么的?与传统网络设备的区别
- Websocket技术选型参考