UDP sockets doesnt' work



  • Hi,

    There is some code example that implements WIFI-Direct using UDP?

    Recevier

            wlan =WLAN()
    
            Pin('P12', mode=Pin.OUT)(True)
            wlan.init(mode=WLAN.AP, ssid= Name, auth=(WLAN.WPA2,Pass), channel=1, antenna=WLAN.EXT_ANT)
            s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)  #create  socket server
            s.bind(('192.168.4.1',2000))  #bind
            s.settimeout(3)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            while True:
               try:
                data, address = sock.recvfrom(1024)
                print ("Received data from", address)
                print(data)
                ack = bytes("ACK",'utf-8')
                s.sendto(ack,('192.168.4.2', 58308))  #invia l'ack
               except OSError:
                       return ("Timeout")
            
    

    Sender

        Pin('P12', mode=Pin.OUT)(True)
        wlan = WLAN()
        wlan.init(mode = WLAN.STA, antenna = WLAN.EXT_ANT) #station
        wlan.ifconfig(config=('192.168.0.107', '255.255.255.0', '192.168.0.1', '192.168.0.1'))
        nets = wlan.scan()
    
    
        for net in nets:
            if net.ssid == ssid:
                print("Found network: " + net.ssid)
                wlan.connect(net.ssid, auth=(net.sec, password), timeout=5000) 
    
                while not wlan.isconnected():
                    idle() # save energy
                if wlan.isconnected() == True:
                        print('WLAN connection succeeded!')
        data = "Hello"
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)  #crea  socket server
        s.bind('192.168.0.107',58308)
        s.settimeout(3)
        s.sendto(data,('192.168.4.1',2000))   #send bytes
        print("Waiting for the data")
    
        while True:
         try:
    
            result, address = s.recvfrom(1024)
            print(address)
            if address == ('192.168.4.1',2000):
                print(result)
                return result
            else:
                return -1
    
         except OSError:
    
            print ("Timeout")
            return "Timeout"
    

    But the sockets doesn't exchange data, what is wrong?
    (obviously all the necessary modules have been imported)



  • @tvetter1976

    Hi,

    I've added the timeout to make the recvfrom non-blocking.Moreover, all the operation does not depend by the s.bind() (for safety I tried to remove it anyway, and in fact it still doesn't work)
    Other advice?

    Thank you



  • @p-m-97
    For the sender, this should be enough for sending data (bind and timeout is not needed for UDP as far as I understood):

    
    UDP_IP = '192.168.4.1'
    UDP_PORT = 2000
    MESSAGE = "Hello, World!".encode()
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    addr=(UDP_IP,UDP_PORT)
    s.sendto(MESSAGE,addr)

Log in to reply
 

Pycom on Twitter