基于socketserver实现的并发(tcp和udp)

threading 线程

基于tcp协议:请求建立连接,然后开启进程

基于udp协议:直接开启新进程

 

基于tcp协议

 

import socketserver  # 导入socketserver模块
# socketsever 把并发进程的方法封装
class MyHandler(socketserver.BaseRequestHandler):  # 定义一个类,继承父类BaseRequestHandler 
    # 父类里有request和client_address 属性
    def handle(self):
        #通信循环
        while True:
            # print(self.client_address)
            # print(self.request) #self.request=conn

            try:
                data=self.request.recv(1024)  # self.request = conn 
                if len(data) == 0:break
                self.request.send(data.upper())
            except ConnectionResetError:
                break


if __name__ == '__main__':
    # s=socketserver.ThreadingTCPServer(请求处理类  服务端地址)

    s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyHandler,bind_and_activate=True)
    print(s) # <socketserver.ThreadingTCPServer object at 0x000002164C8D4898>

    s.serve_forever()  # 代表连接循环

    # 循环建立连接,每建立一个连接就会启动一个线程(服务员)和
    # 调用Myhandler类产生一个对象,调用该对象下的handle方法,专门与刚刚建立好的连接做通信循环
基于socketsever服务端
import socket

phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080)) # 指定服务端ip和端口

while True:
    # msg=input('>>: ').strip() #msg=''
    msg = 'client33333'  # msg=''
    if len(msg) == 0:continue
    phone.send(msg.encode('utf-8'))
    data=phone.recv(1024)
    print(data)


phone.close()
基于socketserver客户端

 

基于udp协议

import socketserver

class MyHandler(socketserver.BaseRequestHandler):
    def handle(self):
        #通信循环
        print(self.client_address)
        print(self.request) # 元组形式,第一个是客户端发来的请求,第二个是套接字对象

        data=self.request[0]
        print('客户消息',data)
        self.request[1].sendto(data.upper(),self.client_address) # 套接字对象(数据,客户端地址)
        
# (b'client444444', <socket.socket fd=424, family=AddressFamily.AF_INET,
#  type=SocketKind.SOCK_DGRAM, proto=0, laddr=('127.0.0.1', 8080)>)
# 客户消息 b'client444444'
# ('127.0.0.1', 54288)

if __name__ == '__main__':
    s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyHandler)
    s.serve_forever()
基于socketserver服务端
import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #数据报协议-》udp

while True:
    # msg=input('>>: ').strip() #msg=''
    msg='client444444'

    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    data,server_addr=client.recvfrom(1024)
    print(data)

client.close()
基于socketserver客户端

 

posted @ 2018-07-10 16:48  Roc_Atlantis  阅读(222)  评论(0编辑  收藏  举报