Socket

Implement UDP communication using Socket.

Get Local IP Address


# Get local IP address
from wifiCfg import wlan_sta

print(wlan_sta.ifconfig())

UDP Server


import socket

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

print(socket.AF_INET)

# Listen on host and port
udpsocket.bind(('0.0.0.0', 5000))

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

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

UDP Client


import socket

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

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

# Send data
udpsocket.send(DATA)

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

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