其他分享
首页 > 其他分享> > 基于socketserver模块实现并发

基于socketserver模块实现并发

作者:互联网

基于tcp协议的使用:

 

服务端

import socketserver

class MyRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        print(self.request)
        print(self.client_address)

        while True:
            try:
                data = self.request.recv(1024)
                if len(data) == 0:break
                print('客户端发来的消息是:',data.decode('utf-8'))
                self.request.send(data.upper())
            except Exception:
                break
        self.request.close()
s = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyRequestHandler)
s.serve_forever()

客户端

 

import socket

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))

while True:
    msg = input('cmd:').strip()
    if len(msg) == 0:continue
    client.send(msg.encode('utf-8'))
    data = client.recv(1024)
    print('服务端发来的消息是:',data.decode('utf-8'))
client.close()

 

 

基于udp协议的使用:

服务端

import socketserver

class MyRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        client_data = self.request[0]
        server = self.request[1]
        client_address = self.client_address
        print('客户端发来的数据:%s' %client_data)

        server.sendto(self.request[0].upper(),client_address)

s = socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyRequestHandler)
s.serve_forever()   #只负责循环的收

# while True:
#     data,client_addr = server.recvfrom(1024)
#     # 每收到一个消息,启动一个线程去处理后续的事情
#     print(data)
#     server.sendto(data.upper(),client_addr)

客户端

import socket

sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

while True:
    msg= input('>>>>>>:').strip()
    sk.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    res = sk.recvfrom(1024)
    print(res)
sk.close()

 

标签:socket,socketserver,self,并发,client,模块,print,data
来源: https://www.cnblogs.com/MRPython/p/15124243.html