Socket

Use Socket to achieve UDP communication

Get the local IP


#Get local IP
from wifiCfg import wlan_sta

print(wlan_sta.ifconfig())

UDP Server


import socket

#Create Socket instance
udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print(socket.AF_INET)

#Monitor Host and Port
udpsocket.bind(('0.0.0.0', 5000))

#Send data to the specified IP and port
udpsocket.sendto(data, (IP, 5000))

while True:
   #Receive 1024 bytes data
   print(udpsocket.recv(1024))
   wait_ms(2)

UDP Client


import socket

#Create Socket instance
udpsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

#Configure the connection to specify the UDP server IP and port
udpsocket.connect((IP, 5000))

#send data
udpsocket.send(DATA)

#Send data to the specified UDP server
udpsocket.sendto(DATA, (IP, 5000))

while True:
   #Receive 1024 bytes data
   print(udpsocket.recv(1024))
   wait_ms(2)
On This Page