socketserver模块
Server类
server.py
from socket import * ip_port = ('127.0.0.1', 8800) tcp_socket_server = socket() tcp_socket_server.bind(ip_port) tcp_socket_server.listen(5) while 1: conn, addr = tcp_socket_server.accept() print('客户端',addr) while 1: client_data = conn.recv(1024) print(client_data.decode("utf-8")) if client_data.decode("utf-8") == "exit": print("客户端断开连接,等待新的用户连接") break print('接收数据>>>',str(client_data, "utf8")) response = input("响应数据>>>") conn.sendall(bytes(response, "utf8")) conn.close()
多高并发的:
client.py
import socket ip_port = ('127.0.0.1', 8880) sock = socket.socket() sock.connect(ip_port) print("客户端启动:") while True: inp = input('发送数据>>>') sock.sendall(bytes(inp, "utf8")) if inp == "exit": break server_response=sock.recv(1024) print("服务器响应数据>>>", str(server_response,"utf8"))
socker_server.py
import socketserver ''' socketserver使用模式 功能类 class MyServer(socketserver.BaseRequestHandler): #继承这个类 def handle(self): pass server = socketserver.ThreadingTCPServer(('127.0.0.1', 8800), MyServer) server.serve_forever() ''' class MyServer(socketserver.BaseRequestHandler): #继承这个类 def handle(self): """ 并发的业务逻辑 conn :return: """ while 1: client_data = self.request.recv(1024) print(client_data.decode("utf-8")) if client_data.decode("utf-8") == "exit": print("客户端断开连接,等待新的用户连接") break print('接收数据>>>',str(client_data, "utf8")) response = input("响应数据>>>") self.request.sendall(bytes(response, "utf8")) self.request.close() #1 self.socket 2 self.socket.bind() 3 self.socket.listen(5) (初始化的过程中它帮我们做了这3件事情) server = socketserver.ThreadingTCPServer(('127.0.0.1', 8880), MyServer) #封装TCP协议相关的套接字对象 server.serve_forever()
这里ThreadingTCPServer是基于TCP, 也有基于UDP的ThreadingUDPServer ---->>>多线程并发
ForkingTCPServer ----->>> 多进程并发的,创建的是多进程而不是多线程了