Python随心记--socketserver:实现并发

时间:2021-10-15 23:59:34

#服务端

import socketserver

class Myserver(socketserver.BaseRequestHandler):
    def handle(self):

        print(self.request)   #conn  连接
        print(self.client_address)  #addr  地址

        while True:
            try:
                data = self.request.recv(1024)   #接收消息
                if not data:break
                print('收到客户端的消息是',data)
                self.request.sendall(data.upper())   #发消息
            except Exception as e:
                break;

if __name__ == '__main__':
    s = socketserver.ThreadingTCPServer(('127.0.0.1',8080),Myserver)
    s.serve_forever()

客服端1

from socket import *
import struct
from functools import partial
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024

tcp_client=socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)

while True:
    msg=input('>>: ').strip()
    if not msg:continue
    if msg == 'quit':break

    tcp_client.send(msg.encode('utf-8'))

    data = tcp_client.recv(buffer_size)
    print(data)

tcp_client.close()

客户端2

from socket import *
import struct
from functools import partial
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024

tcp_client=socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)

while True:
    msg=input('>>: ').strip()
    if not msg:continue
    if msg == 'quit':break

    tcp_client.send(msg.encode('utf-8'))

    data = tcp_client.recv(buffer_size)
    print(data)

tcp_client.close()