jueqingsizhe66 / jueqingsizhe66.github.io

my hugo blogs
0 stars 0 forks source link

post/socket%E6%9D%A5%E6%BA%90/ #16

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Socket来源 | 30年磨一剑

socket client和server的单人对话 socket client和ser

https://jueqingsizhe66.github.io/post/socket%E6%9D%A5%E6%BA%90/

jueqingsizhe66 commented 2 years ago

可以通过socketserver.ThreadingTCPServer实现多线程并发操作

jueqingsizhe66 commented 2 years ago

所有web框架的本源都是socket编程,就是下面的15行代码

  import socket
  def handle_request(client):
      buf = client.recv(1024)
      client.send("HTTP/1.1 200 OK\r\n\r\n")
      client.send("Hello socket")
  def main():
      sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
      sock.bind(("localhost",8989)) ## 绑定端口
      sock.listen(5) ## python3没有限制监听个数
      while True: ##不断监听
          connection,address=sock.accept() ## 浏览器输入localhost:8989 或者python新建一个客户端socket
          handle_request(connection)
          connection.close() ## 断开资源
  if __name__ =="__main__":
      main()
jueqingsizhe66 commented 2 years ago

https://jueqingsizhe66.github.io/post/socket%E5%88%86%E5%8C%85%E7%B2%98%E5%8C%85/

jueqingsizhe66 commented 2 years ago
  from wsgiref.simple_server import make_server
  def RunServer(environ, start_response):
      ## environ返回客户端所有请求数据
      ## start_response 封装返回给用户的数据 响应头信息
      start_response("200 OK",[('Content-Type','text/html')])
      ## 返回渲染内容
      #return '<h1> Hello ,Web!</h1>' ## py2  py2没有字节概念
      return ['<h1> Hello ,Web!</h1>'.encode('utf-8')]##py3  py3有字节,基本上都变成字节,没有unicode了,  encode作用就是转化为字节

  if __name__ =='__main__':
      htpd=make_server('',8989,RunServer) ## 不用创建socket了
      print("Serving HTTP on port 8989") ##py3
      httpd.serve_froever()