1.多线程模块
主要是socketserver模块,如下图示:
2.多线程原理
如下图示说明:
3.SockteServer例子说明
服务器端:
客户端:
4.演示
还是以前面例子,对代码进行修改,作如下的演示。
Server端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import SocketServer #导入SocketServer,多线程并发由此类实现
class MySockServer(SocketServer.BaseRequestHandler): #定义一个类
def handle(self): #handle(self)方法是必须要定义的,可以看上面的说明
print 'Got a new connection from' , self.client_address
while True:
data = self.request.recv( 1024 ) #需要通过self的方法调用数据接收函数
if not data: break
print 'recv:' , data
self.request.send(data.upper()) #需要通过self的方法调用数据接收函数
if __name__ == '__main__' : #并非一定要用这样的方式,只是建议这样使用
HOST = '' #定义侦听本地地址口(多个IP地址情况下),这里表示侦听所有
PORT = 50007 #Server端开放的服务端口
s = SocketServer.ThreadingTCPServer((HOST, PORT), MySockServer)
#调用SocketServer模块的多线程并发函数
s.serve_forever() #持续接受客户端的连接
|
Client端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import socket
HOST = '192.168.1.13'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while True:
user_input = raw_input( 'msg to send:' ).strip()
s.sendall(user_input)
data = s.recv( 1024 )
print 'Received' , repr(data)
s.close() |
演示:
步骤1:Server端运行服务端程序
1
2
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py ===>光标在此处处于等待状态 |
步骤2:Client A端运行客户端程序
1
2
3
4
5
6
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python client4.py msg to send:Hello! ===>User输入数据 Received 'HELLO!' ===>Server端返回的数据
msg to send:I'm Client A. Received "I'M CLIENT A."
msg to send: ===>继续等待User输入数据 |
步骤3:在Server端中观察现象
1
2
3
4
5
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py Got a new connection from ( '192.168.1.13' , 52650 )
recv: Hello! recv: I'm Client A. ===>接收到Client A端发送的数据 ===>光标在此处处于等待状态 |
1
2
3
4
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python client4.py msg to send:I'm Client B. ===>User输入数据 Received "I'M CLIENT B." ===>Server端返回的数据
msg to send: ===>继续等待User输入数据 |
步骤5:在Server端中观察现象
1
2
3
4
5
6
7
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py Got a new connection from ( '192.168.1.13' , 52650 )
recv: Hello! recv: I'm Client A. Got a new connection from ( '192.168.1.13' , 52651 )
recv: I'm Client B. ===>接收到Client A端发送的数据 ===>光标在此处处于等待状态 |
通过上面的演示,使用SocketServer便可以实现Python Socket的多线程并发。
本文转自 xpleaf 51CTO博客,原文链接:http://blog.51cto.com/xpleaf/1700042,如需转载请自行联系原作者