Socket网络编程

http://www.cnblogs.com/alex3714/articles/5830365.html

 

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
self.request.send(self.data.upper())
except ConnectionResetError as e:
print("err",e)
break
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()

步骤
1、创建一个处理类
2、重写方法handle
3、是少一个实例化
4、server.serve_forever() #处理多个一个请求,永远执行

First, you must create a request handler处理类 class by subclassing the BaseRequestHandler class and overriding覆盖 its handle() method; this method will process incoming requests.   
你必须自己创建一个请求处理类,并且这个类要继承BaseRequestHandler,并且还有重写父亲类里的handle()
Second, you must instantiate实例化 one of the server classes, passing it the server’s address and the request handler class.
你必须实例化TCPServer ,并且传递server ip 和 你上面创建的请求处理类 给这个TCPServer
Then call the handle_request() or serve_forever() method of the server object to process one or many requests.
server.handle_request() #只处理一个请求
server.serve_forever() #处理多个一个请求,永远执行
posted @ 2018-11-17 15:24  rongye  阅读(109)  评论(0编辑  收藏  举报