UDP Client/Server Socket in Python

前端 未结 3 543
自闭症患者
自闭症患者 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()
    
    0 讨论(0)
  • 2020-12-04 20:48

    I believe you are trying to subtract from pings at the end instead of your intended increments as written by your while statement.

    0 讨论(0)
  • 2020-12-04 20:55

    I tested your code, and it works as expected on my machine. Your issue might not be your code. It could be a firewall or something else blocking all the packets on the loopback interface (127.0.0.1). Depending on your operating system, try testing with a packet monitor like Wireshark.

    Also, here are a few suggestions on how to improve your code to be more Pythonic:

    Server

    import random
    import socket
    
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_socket.bind(('', 12000))
    
    while True:
        rand = random.randint(0, 10)
        message, address = server_socket.recvfrom(1024)
        message = message.upper()
        if rand >= 4:
            server_socket.sendto(message, address)
    

    Client

    import time
    import socket
    
    for pings in range(10):
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        client_socket.settimeout(1.0)
        message = b'test'
        addr = ("127.0.0.1", 12000)
    
        start = time.time()
        client_socket.sendto(message, addr)
        try:
            data, server = client_socket.recvfrom(1024)
            end = time.time()
            elapsed = end - start
            print(f'{data} {pings} {elapsed}')
        except socket.timeout:
            print('REQUEST TIMED OUT')
    
    0 讨论(0)
提交回复
热议问题