python socketserver编程

socket并不能多并发,只能支持一个用户,socketserver可以实现并发, 简化了编写网络服务程序的任务,socketserver是socket的在封装。socketserver中包含了两种类,一种为服务类(server class),一种为请求处理类(request handle class)。前者提供了许多方法:像绑定,监听,运行…… (也就是建立连接的过程) 后者则专注于如何处理用户所发送的数据(也就是事务逻辑)。

创建socketserver的步骤:

First, you must create a request handler class by subclassing the BaseRequestHandlerclass and overriding its handle() method; this method will process incoming requests.   
Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class.
Then call the handle_request() or serve_forever() method of the server object to process one or many requests.
Finally, call server_close() to close the socket.

server端:

import socketserver
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        print('server端启动')
        while True:
       # self.request is the TCP socket connected to the client
       #!!!!!!!!

            conn=self.request
            print(self.client_address)
            while True:
                client_data=conn.recv(1024)
                print(str(client_data,'utf8'))
                inp=input('>>>>')
                conn.send(bytes(inp,'utf8'))
            conn.close()
if __name__=='__main__':
    server=socketserver.ThreadingTCPServer(('127.0.0.1',8002),MyServer)
    server.serve_forever()

client端:
import socket
sk=socket.socket()
sk.connect(('127.0.0.1',8002))
print('client启动')
while True:
    inp=input('>>>>')
    sk.send(bytes(inp,'utf8'))
    server_response=sk.recv(1024)
    print(str(server_response,'utf8'))
    if inp=='q':
        break
sk.close()
写出漂亮的博客就是为了以后看着更方便的。
原文地址:https://www.cnblogs.com/zhaowei5/p/9295783.html