python 多线程实现多客户端连接的 TCP Server
2017-01-23 20:25
666 查看
python 多线程实现多客户端连接的 TCP Server
最近看《python核心编程》,书中实现了一个简单的1对1的TCPserver,但是在实际使用中1对1的形势明显是不行的,所以研究了一下如何在server端通过启动不同的线程(进程)来实现每个链接一个线程。其实python在类的设计上已经考虑到了这一方面的需求,我们只要在自己的server上继承一下SocketServer.BaseRequestHandler就可以了。
server端代码如下:
#!/usr/bin/env python import SocketServer from time import ctime HOST = '' PORT = 21567 ADDR = (HOST, PORT) class MyRequestHandler(SocketServer.BaseRequestHandler): def handle(self): print '...connected from:', self.client_address while True: self.request.sendall('[%s] %s' % (ctime(),self.request.recv(1024))) tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler) print 'waiting for connection...' tcpServ.serve_forever()
客户端代码如下(基本和书中一模一样,只是把循环中的关闭链接注释掉了):
#!/usr/bin/env python from socket import * HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) while True: tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) data = raw_input('> ') if not data: break tcpCliSock.send('%s\r\n' % data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data.strip() #tcpCliSock.close()
from :https://my.oschina.net/leejun2005/blog/104727
相关文章推荐
- [置顶] 使用多线程实现多客户端的连接(通过Socket实现TCP编程)
- python---TCP UDP IPv4 IPv6 客户端和服务端的实现
- Python使用TCPServer编写(多线程)Socket服务
- python实现TCP服务器端与客户端的方法详解
- 使用Python SocketServer快速实现多线程网络服务器
- python网络编程(TCP客户端/服务器端实现)
- TCP--通过多线程实现客户端并发上传图片
- 由 TIdTCPServer 提供客户端安装程序 WEB 下载的实现方法
- python实现TCP服务器端与客户端的方法详解
- Python使用TCPServer编写(多线程)Socket服务
- 利用Python中SocketServer 实现客户端与服务器间非阻塞通信
- How to release the port of TCP Client immediately when the connection is disconnect with the TCP server. - TCP 客户端与 TCP 服务器断开连接后
- [CODE] 通过tcpserver实现对同一IP的最大连接数和连接频率的限制
- 用Python实现一个简单的多线程TCP服务器的教程
- 网络编程资料总结(二)----Tcp多线程服务器和客户端的实现
- RTSP客户端模拟器(TCP方式,Python实现)
- python 网络编程(三)---TCP 服务器端客户端实现
- Python使用TCPServer编写(多线程)Socket服务
- Python实现TCP\UDP客户端
- 用Python实现一个简单的多线程TCP服务器的教程