UDP Client/Server Socket in Python

前端 未结 3 569
自闭症患者
自闭症患者 2020-12-04 20:23

I\'m new to python and sockets and am trying to write an echoing client/server socket. I have written the server so that 30% of the packets are lost. I programmed my client

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 20:44

    Here is an alternative with asyncio.

    import asyncio
    import random
    
    class EchoServerProtocol:
        def connection_made(self, transport):
            self.transport = transport
    
        def datagram_received(self, data, addr):
            message = data.decode()
            print('Received %r from %s' % (message, addr))
            rand = random.randint(0, 10)
            if rand >= 4:
                print('Send %r to %s' % (message, addr))
                self.transport.sendto(data, addr)
            else:
                print('Send %r to %s' % (message, addr))
                self.transport.sendto(data, addr)
    
    
    loop = asyncio.get_event_loop()
    print("Starting UDP server")
    
    # One protocol instance will be created to serve all client requests
    listen = loop.create_datagram_endpoint(
        EchoServerProtocol, local_addr=('127.0.0.1', 12000))
    transport, protocol = loop.run_until_complete(listen)
    
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    
    transport.close()
    loop.close()
    

提交回复
热议问题