Python 官方文档:入门教程 => 点击学习
从网上参考了一些代码,实现了一个python实现的基于线程的Socket server, 用来实现各种服务系统的原型。放在这里供以后参考。 #!/usr/bin/env Python import threading&
从网上参考了一些代码,实现了一个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()
--结束END--
本文标题: Python thread socket
本文链接: https://lsjlt.com/news/191530.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0