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)
  • 相关阅读:
    Failed to rename HdfsNamedFileStatus
    C#多线程编程(4)--异常处理+前三篇的总结
    React Native =>(箭头函数)
    React Native undefined和null
    React Native 生命周期
    React Native Invariant Violation: Text strings must be rendered within a <Text> component.
    React Native 布局 justifyContent、alignItems、alignSelf、alignContent
    React Native 实现垂直水平居中(justifyContent、alignItems)
    React Native TypeError:undefined is not an object
    React Native 自定义动态标签
  • 原文地址:https://www.cnblogs.com/bxhsdy/p/13330189.html
Copyright © 2011-2022 走看看