zoukankan      html  css  js  c++  java
  • Python socket学习笔记(三)

    之前都是客户端对服务器的单线程操作。接下来学习 SocketServer 多线程

    SockServer

    class SocketServer.BaseServer
    SocketServer.BaseRequestHandler   The request handler class must define a new handle()
    
    
    RequestHandler.Handle()
    This function must do all the work required to service a request. The default implementation dose nothing.Several instance attributes are available to it; the request is available as self.request;the clinet address as self.client_address;and the server instance as self.server, in case it needs access to per-server information
    
    
    RequestHandler.setup()
    Called before the handle() method to perform any initialization actions required. The default implementation does nothing.
    
    
    BaseServer.serve_forever(poll_interval=0.5)
    Handle requesets until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores self.timeout.If you need to do periodic tasks,do them in another thread.

    多线程的连接过程:

    SocketServer 例子

    服务器端

    import SocketServer
    class MyTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
      while 1:
        self.data=self.request.recv(1024).strip()
        print ("{} wrote:".format(self.client_address[0]))
        if not self.data:break
        self.request.sendall(self.data.upper())

    if __name__ == "__main__":

      HOST,PORT = "localhost",9999
      server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
      server.serve_forever()

    client (也可以使用之前的客户端程序,只要改下端口即可)

    import  socket,sys
    HOST,PORT = "localhost",9999
    data = " ".join(sys.argv[1:])
    
    #create a socket (SOCK_STREAM means a TCP socket)
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    try:
        #Connect to server and send data
        sock.connect((HOST,PORT))
        sock.sendall(data + "
    ")
        
        # Receive data from the server and shutdown
        received = sock.recv(1024)
    finally:
        sock.close()
    
    print("Sent: {}".format(data))
    print("Received: {}".format(received)
  • 相关阅读:
    Oracle 列转行函数 Listagg()
    JS正则表达式
    云经验
    业务架构、应用架构、数据架构和技术架构
    Sublime Text3+Golang搭建开发环境
    成功安装vscode中go的相关插件
    Visual Studio Code配置GoLang开发环境
    团队架构实践
    架构
    条件引用
  • 原文地址:https://www.cnblogs.com/bxhsdy/p/13330189.html
Copyright © 2011-2022 走看看