• Feeds

  • Python thread socket server

    从网上参考了一些代码,实现了一个Python实现的基于线程的socket server, 用来实现各种服务系统的原型。放在这里供以后参考。

    #!/usr/bin/env python
    import threading
    import SocketServer
    
    users = []
    
    class MyTCPHandler(SocketServer.StreamRequestHandler):
        def handle(self):
            username = None
            while True:
                self.data = self.rfile.readline().strip()
                cur_thread = threading.currentThread()
                print "RECV from ", self.client_address[0]
                cmd = self.data
                if cmd == None or len(cmd) == 0:
                    break;
                print cmd
                # business logic here
                try:
                    if cmd.startswith('echo'):
                        result = cmd[5:]
                    elif cmd.startswith('login'):
                        username = cmd[6:]
                        users.append({username:self.wfile})
                        result = username + ' logined.'
                    elif cmd == 'quit':
                        break
                    else:
                        result = 'error cmd'
                    self.wfile.write(result)
                    self.wfile.write('\n')
                except:
                    print 'error'
                    break
            try:
                if username != None:
                    users.remove(username)
            except:
                pass
            print username, ' closed.'
    
    class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
        pass
    
    if __name__ == "__main__":
        HOST, PORT = "localhost", 9999
    
        server = ThreadedTCPServer((HOST, PORT), MyTCPHandler)
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.setDaemon(True)
        server_thread.start()
        server.serve_forever()

    如想及时阅读Tim Yang的文章,可通过页面右上方扫码订阅最新更新。

    « | »

    30 Comments  »

    1. zkd

      想请问下,为什么在线程里面调用了serve_forever,后面再调用一次这个函数。如果仅仅是为了不让进程结束,为什么不直接server_thread.setDaemon(False)?

    2. wale

      同疑惑
      根据官方文档的同样用法,并没有server.serve_forever()这一句.

      # Start a thread with the server — that thread will then start one
      # more thread for each request
      server_thread = threading.Thread(target=server.serve_forever)
      # Exit the server thread when the main thread terminates
      server_thread.setDaemon(True)
      server_thread.start()

      from:http://docs.python.org/library/socketserver.html

    3. 回忆书签

      应该改为
      server_thread = threading.Thread(target=server.serve_forever())

    4. Michael

      #!/usr/bin/env python
      #coding:utf-8
      #Filename : ThraedingSocketServer.py

      import sys,SocketServer
      import threading

      class MyTCPSocketServerHandler(SocketServer.BaseRequestHandler):
      “””
      The RequestHandler class for our server.

      It is instantiated once per connection to the server, and must
      override the handle() method to implement communication to the
      client.
      “””
      def handle(self):
      #self.request是处理来自客户端的原始类
      self.data = self.request.recv(1024).strip()
      print “{0} wrote :”.format(self.client_address[0])
      print self.data

      #收到数据后,回包
      self.request.sendall(self.data.upper())

      class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer):
      pass

      if __name__ == “__main__”:
      HOST,PORT = “localhost”,8899
      server = ThreadedTCPServer((HOST,PORT),MyTCPSocketServerHandler)

      server_thread = threading.Thread(target=server.serve_forever())
      server_thread.daemon = True
      server_thread.start()

      print “Server is loop running in “,server_thread.name

    5. 前几天刚开始练习 python,现在遇到验证码问题,网上查了下教程,了解到用python获取验证码还是不少.自己琢磨了整个晚上,用的是开源的打码工具tesseractor,但最后都没成功,不知道是什么问题

    6. I believe other website proprietors should take this site as an model, very clean and
      wonderful user pleasant layout.

    7. Hmm it seems like your blog ate my first comment (it was extremely long)
      so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying
      your blog. I too am an aspiring blog blogger but I’m still new to everything.
      Do you have any points for rookie blog writers?
      I’d definitely appreciate it.

    8. Thanks for any other informative web site.
      The place else could I get that type of information written in such an ideal way?
      I’ve a undertaking that I’m just now running on, and I have been at the look out
      for such information.

    9. laser-projected virtual keyboard and piano.

    10. Buy & sell Crypto in minutes P2PB2B p2pb2b exchange review trading is easy with our simple interface.

    11. @Canal EDM : D

      my blog post home

    12. Watch porn videos anal

    13. Henry

      Thanks for sharing this script with my fence installer. This is very helpful!

    14. Julius

      I appreciate the clear structure of your code, especially the threaded approach to handle multiple client connections concurrently. ROOFING REPAIR COTGRAVE

    15. Jeffrey

      Thanks for including comments within the code to explain different sections. It makes it easier for others to understand the logic and customize it for their needs. ROOFING REPAIR KEYWORTH

    16. Ryan

      It’s great to see the inclusion of error handling in your code, ensuring a more robust and reliable server implementation.

      ROOFING REPAIR CLIFTON

    17. Jacob

      Thanks for providing this script—it’s a practical starting point for anyone looking to develop a simple socket server with thread support in Python. ROOFING REPAIR BEESTON

    18. Seeking opinions: What CBD gummies do you suggest for pain management?

    19. Wondering aloud: Does anyone have suggestions for top-notch CBD gummies?

    20. Seeking input: Does anyone have personal preferences for the best CBD oil?

    21. Open to recommendations: Could someone suggest something satisfying?

    22. In need of guidance: Does anyone recommend specific brands for the best CBD gummies?

    23. MathCat

      My car blog: блог

    24. Janus

      It is instantiated once per connection to the server, and must
      override the handle() method to implement communication to the
      client.

      concrete steps pearland

    25. Awesome post! Thanks for the great content you shared here.

    26. A limo might be the perfect finishing touch for my romantic evening plans. Is there anything you can think of to make the trip more memorable? Seeking original suggestions!

    27. Wow. I must share this learning with the landscaping nearby for reference. Thanks!

    Leave a Comment