#自定义一个与sock server类相似的功能
#server.py import socket from multiprocessing import Process class makeServer(object):#创建服务类 def __init__(self,ip,port): #初始化方法 self.ip=ip self.port=port def makeAnServer(self):#开启服务 server=socket.socket() server.bind((self.ip,self.port)) server.listen(100) return server def forever(self,server):#一直服务下去 while 1: conn, addr = server.accept()#等待连接 p = myProcess(conn, addr)#创建一个进程 p.start()#开启进程 class myProcess(Process):#自定义进程类 def __init__(self,conn,addr):#初始化进程 super().__init__()#先进性父类的init self.conn=conn self.addr=addr def run(self):#运行进程 print('连接成功。。。') recv_data=self.conn.recv(1024).decode('gbk') print('recv_data:',recv_data) self.conn.send('你好'.encode('gbk')) if __name__ == '__main__': obj=makeServer('127.0.0.1',8001)#实例化对象 server=obj.makeAnServer()#开启服务 obj.forever(server)#一直服务下去 #client.py import socket client=socket.socket() client.connect(('127.0.0.1',8001)) content=input('请输入内容:') client.send(content.encode('gbk')) recv_data=client.recv(1024).decode('gbk') print(recv_data)
#系统socket server模块
import socketserver class myServer(socketserver.BaseRequestHandler): def handle(self): #self.request 就是conn pass if __name__=="__main__": socketserver.TCPServer.allow_reuse_address=True server=socketserver.ThreadingTCPServer(('127.0.0.1',8001),myServer) server.server_forever()