标签:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/usr/bin/env python # -*- coding:utf-8 -*- import SocketServer class MyServer(SocketServer.BaseRequestHandler): def handle( self ): #函数名必须是handle,源码BaseRequestHandler预定义; print self .request, self .client_address, self .server #BaseRequestHandler的__init__定义好的; conn = self .request #每个连接的socket conn.sendall( ‘欢迎致电 10086,请输入1xxx,0转人工服务.‘ ) Flag = True while Flag: data = conn.recv( 1024 ) if data = = ‘exit‘ : Flag = False elif data = = ‘0‘ : conn.sendall( ‘通话可能会被录音.balabala一大推‘ ) else : conn.sendall( ‘请重新输入.‘ ) if __name__ = = ‘__main__‘ : server = SocketServer.ThreadingTCPServer(( ‘127.0.0.1‘ , 8009 ),MyServer) #实例化ThreadingTCPServer,其实是继承TCPServer类的初始化,需要传入(server_address, RequestHandlerClass),RequestHandlerClass就是MyServer类。 server.serve_forever() #启动服务,用select一直在循环执行,继承自BaseServer类的方法serve_forever(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/env python # -*- coding:utf-8 -*- import socket ip_port = ( ‘127.0.0.1‘ , 8009 ) sk = socket.socket() sk.connect(ip_port) sk.settimeout( 5 ) while True : data = sk.recv( 1024 ) print ‘receive:‘ ,data inp = raw_input ( ‘please input:‘ ) sk.sendall(inp) if inp = = ‘exit‘ : break sk.close() |
server = SocketServer.ThreadingTCPServer((‘127.0.0.1‘,8009),MyRequestHandler)
变更为:
server = SocketServer.ForkingTCPServer((‘127.0.0.1‘,8009),MyRequestHandler)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import socket import threading import select def process(request, client_address): print request,client_address conn = request conn.sendall( ‘欢迎致电 10086,请输入1xxx,0转人工服务.‘ ) flag = True while flag: data = conn.recv( 1024 ) if data = = ‘exit‘ : flag = False elif data = = ‘0‘ : conn.sendall( ‘通过可能会被录音.balabala一大推‘ ) else : conn.sendall( ‘请重新输入.‘ ) sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk.bind(( ‘127.0.0.1‘ , 8002 )) sk.listen( 5 ) while True : r, w, e = select.select([sk,],[],[], 1 ) print ‘looping‘ if sk in r: print ‘get request‘ request, client_address = sk.accept() t = threading.Thread(target = process, args = (request, client_address)) t.daemon = False t.start() sk.close() |
标签:
原文地址:http://www.cnblogs.com/daliangtou/p/5084439.html