【转】https://blog.csdn.net/ghostfromheaven/article/details/8653421#
SocketServer包对socket包进行了包装(封装),使得创建socket服务非常简单。
使用TCPServer和BaseRequestHandler编写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
使用TCPServer和StreamRequestHandler编写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()
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__":
host = "" #主机名,可以是ip,像localhost的主机名,或""
port = 9999 #端口
addr = (host, port)
server = TCPServer(addr, MyStreamRequestHandlerr)
server.serve_forever()
ThreadingTCPServer+StreamRequestHandler=多线程socket
使用ThreadingTCPServer和StreamRequestHandler编写socket服务的样例。ThreadingTCPServer从ThreadingMixIn和TCPServer继承,实现多线程。
#-*- coding:utf-8 -*-
from SocketServer import ThreadingTCPServer, StreamRequestHandler
import traceback
class MyStreamRequestHandlerr(StreamRequestHandler):
def handle(self):
while True:
try:
data = self.rfile.readline().strip()
print "receive from (%r):%r" % (self.client_address, data)
self.wfile.write(data.upper())
except:
traceback.print_exc()
break
if __name__ == "__main__":
host = "" #主机名,可以是ip,像localhost的主机名,或""
port = 9999 #端口
addr = (host, port)
#ThreadingTCPServer从ThreadingMixIn和TCPServer继承
#class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
server = ThreadingTCPServer(addr, MyStreamRequestHandlerr)
server.serve_forever()
多线程socket效果:
image
网友评论