首页 > 编程语言 > 详细

Python使用TCPServer编写(多线程)Socket服务

时间:2014-06-26 19:28:31      阅读:534      评论:0      收藏:0      [点我收藏+]

SocketServer包对socket包进行了包装(封装),使得创建socket服务非常简单。

TCPServer+BaseRequestHandler

使用TCPServerBaseRequestHandler编写socket服务的样例。

 

#-*- coding:utf-8 -*-

from SocketServer import TCPServer, BaseRequestHandler
import traceback

class MyBaseRequestHandlerr(BaseRequestHandler):
    """
    #从BaseRequestHandler继承,并重写handle方法
    """
    def handle(self):
        #循环监听(读取)来自客户端的数据
        while True:
            #当客户端主动断开连接时,self.recv(1024)会抛出异常
            try:
                #一次读取1024字节,并去除两端的空白字符(包括空格,TAB,\r,\n)
                data = self.request.recv(1024).strip()
                
                #self.client_address是客户端的连接(host, port)的元组
                print "receive from (%r):%r" % (self.client_address, data)
                
                #转换成大写后写回(发生到)客户端
                self.request.sendall(data.upper())
            except:
                traceback.print_exc()
                break

if __name__ == "__main__":
    #telnet 127.0.0.1 9999
    host = ""       #主机名,可以是ip,像localhost的主机名,或""
    port = 9999     #端口
    addr = (host, port)
    
    #购置TCPServer对象,
    server = TCPServer(addr, MyBaseRequestHandlerr)
    
    #启动服务监听
    server.serve_forever()

 

  

TCPServer+StreamRequestHandler

 

使用TCPServerStreamRequestHandler编写socket服务的样例。StreamRequestHandler从BaseRequestHandler,并做了封装,使得读写数据更容易。

 

#-*- coding:utf-8 -*-

from SocketServer import TCPServer, StreamRequestHandler
import traceback

class MyStreamRequestHandlerr(StreamRequestHandler):
    """
    #StreamRequestHandler,并重写handle方法
    #(StreamRequestHandler继承自BaseRequestHandler)
    """
    def handle(self):
        while True:
            #客户端主动断开连接时,self.rfile.readline()会抛出异常
            try:
                #self.rfile类型是socket._fileobject,读写模式是"rb",方法有
                #read,readline,readlines,write(data),writelines(list),close,flush
                data = self.rfile.readline().strip()
                
                #self.client_address是客户端的连接(host, port)的元组
                print "receive from (%r):%r" % (self.client_address, data)
                
                #self.wfile类型是socket._fileobject,读写模式是"wb"
                self.wfile.write(data.upper())
            except:
                traceback.print_exc()
                break

if __name__ == "__main__":
    #telnet 127.0.0.1 9999
    host = ""       #主机名,可以是ip,像localhost的主机名,或""
    port = 9999     #端口
    addr = (host, port)
    
    #购置TCPServer对象,
    server = TCPServer(addr, MyStreamRequestHandlerr)
    
    #启动服务监听
    server.serve_forever()

 

 

ThreadingTCPServer+StreamRequestHandler=多线程socket

使用ThreadingTCPServerStreamRequestHandler编写socket服务的样例。ThreadingTCPServer从ThreadingMixIn和TCPServer继承,实现多线程。

 

#-*- coding:utf-8 -*-

from SocketServer import ThreadingTCPServer, StreamRequestHandler
import traceback

class MyStreamRequestHandlerr(StreamRequestHandler):
    """
    #StreamRequestHandler,并重写handle方法
    #(StreamRequestHandler继承自BaseRequestHandler)
    """
    def handle(self):
        while True:
            #客户端主动断开连接时,self.rfile.readline()会抛出异常
            try:
                #self.rfile类型是socket._fileobject,读写模式是"rb",方法有
                #read,readline,readlines,write(data),writelines(list),close,flush
                data = self.rfile.readline().strip()
                
                #self.client_address是客户端的连接(host, port)的元组
                print "receive from (%r):%r" % (self.client_address, data)
                
                #self.wfile类型是socket._fileobject,读写模式是"wb"
                self.wfile.write(data.upper())
            except:
                traceback.print_exc()
                break

if __name__ == "__main__":
    #telnet 127.0.0.1 9999
    host = ""       #主机名,可以是ip,像localhost的主机名,或""
    port = 9999     #端口
    addr = (host, port)
    
    #ThreadingTCPServer从ThreadingMixIn和TCPServer继承
    #class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
    server = ThreadingTCPServer(addr, MyStreamRequestHandlerr)
    
    #启动服务监听
    server.serve_forever()

 

多线程socket效果:

bubuko.com,布布扣

 

样例代码下载

Python使用TCPServer编写(多线程)Socket服务,布布扣,bubuko.com

Python使用TCPServer编写(多线程)Socket服务

原文:http://www.cnblogs.com/bigben0123/p/3808343.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!