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 的文章,可通过页面右上方扫码订阅最新更新。

« | »

Comments

6 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. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *