Blog

UDP Socket Programming in Python

Published 1 min read

Client

# Import the socket module. from socket import * # Set the destination address (IP, Port). # A DNS lookup is done automatically to get the IP from serverName. serverName = "" serverPort = 11111 # Create the client's socket, clientSocket. # AF_INET : address family, indicates the underlying network uses IPv4. # SOCK_DGRAM : means it's a UDP socket. clientSocket = socket(AF_INET, SOCK_DGRAM) # The user enters a message. message = input('Input lowercase sentence:') # Attach the destination address (serverName, serverPort) to the packet (message.encode()) and send it through clientSocket. # The source address is also attached to the packet, but not explicitly in the code; the underlying OS does it automatically. clientSocket.sendto(message.encode(), (serverName, serverPort)) # Wait to receive from the server. # When a packet arrives at the socket from the internet, it's assigned to the variables below. # modifiedMessage : gets the packet data. # serverAddress : gets the packet's source address (the server address). We already know it so it's not needed, but Python provides it. # 2048 : accepts a buffer of this size. modifiedMessage, serverAddress = clientSocket.recvfrom(2048) # The arrived message is printed. print(modifiedMessage.decode()) # Close the socket. clientSocket.close() # The process ends.

Server

from socket import * serverPort = 11111 serverSocket = socket(AF_INET, SOCK_DGRAM) # Assign an address to the socket. serverSocket.bind(("", serverPort)) print("The server is ready to receive") while True: message, clientAddress = serverSocket.recvfrom(2048) modifiedMessage = message.decode().upper() serverSocket.sendto(modifiedMessage.encode(), clientAddress)

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub