Server类

 客户端:

import socket
ip_port=('127.0.0.1',8081)
client=socket.socket()
client.connect(ip_port)
print('客户端启动')
while True:
    msg=input('发送数据>>>').strip()
    if not msg:continue
    if msg=='exit':
        break
    client.send(msg.encode('utf-8'))
    data=client.recv(1024)
    print(data.decode('utf-8'))

服务端:并发

import socketserver
'''
利用socketserver模块实现并发编程

1 功能类
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        pass


2 server=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer)



3 server.serve_forever()

'''
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        '''
        并发的业务逻辑
        conn
        :return:
        '''
        while 1:
            client_data=self.request.recv(1024)

            if client_data.decode('utf-8')=='exit':
                print('客户端断开连接,等待新的用户连接')
                break
            print('接受数据>>>',client_data.decode('utf-8'))
            response=input('响应数据>>>')
            self.request.sendall(response.encode('utf-8'))
        self.request.close()

# 1 self.socket 2 self.socket.blind() 3 SELF.SOCKET.LISTEN(5)
server=socketserver.ThreadingTCPServer(('127.0.0.1',8081),MyServer) # 线程

server.serve_forever()

# 先找self对应的类

----

 

posted on 2018-11-19 15:56  foremost  阅读(496)  评论(0编辑  收藏  举报