Python socket TCPServer Demo

#coding:utf-8
from SocketServer import TCPServer,BaseRequestHandler
import traceback

class MyBaseRequestHandler(BaseRequestHandler):
    """
    #继承BaseRequestHandler的handle方法
    """
    def handle(self):
       while True:
           #当客户端主动断开连接时候,self.recv(1024)会抛出异常
            try:
                data = self.request.recv(1024).strip()
                print "receive for(%r):%r"%(self.client_address,data)
                self.request.sendall(data.upper())
            except:
                traceback.print_exc()
                break


if __name__ == "__main__":
    # 开启ip和端口
    ip_port = ("192.168.1.103", 8090)
    #构造TCPServer对象
    server = TCPServer(ip_port,MyBaseRequestHandler)
    #启动服务器监听
    server.serve_forever()

posted on 2017-09-11 20:59  神秘藏宝室  阅读(505)  评论(0编辑  收藏  举报

 >>>转载请注明出处<<<