create a udp server on a specific port in python

To create a UDP server on a specific port in Python, you can use the built-in socket module. Below is an example code snippet that demonstrates how to create a UDP server on port 1234:

main.py
import socket

# create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# bind the socket to a specific port
server_address = ('localhost', 1234)
sock.bind(server_address)

# listen for incoming messages
while True:
    data, address = sock.recvfrom(1024)
    print("received {} bytes from {}".format(len(data), address))
    print(data)
360 chars
15 lines

In this code snippet, we first create a UDP socket using socket.socket() function. We then specify the socket address family (socket.AF_INET) and the socket type (socket.SOCK_DGRAM), which indicates that we want to create a UDP socket.

Next, we bind the socket to a specific address and port using the bind() method. In this example, we bind the socket to the localhost interface on port 1234.

Finally, we enter a loop to listen for incoming messages using the recvfrom() method. When a message is received, we print the number of bytes received and the message content.

gistlibby LogSnag