Socket programming in python - User Datagram Protocol
Socket Programming UDP
Socket Programming for client-server communication using User-Datagram-Protocol in Python.
UDP client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # Include the socket library for networking import socket import sys # Set server IP address and server socket port number ServerName = 'localhost' # Could be IP address or host name of sever(website) ServerPort = 1234 # integer # Create client socket ClientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4, UDP socket # not specifying client port number, this job is left for the OS to do it for us. # Creating message message = raw_input('Enter lower case sentence: ') # Send the message ClientSocket.sendto(message,(ServerName,ServerPort)) # server address also attached, but not manually, but automatically by the code. #Wait for receiving reply from Server modified_message, ServerAddress = ClientSocket.recvfrom(2048) # reply stored in modified_message # & message source address (not required) anyways stored in ServerAddress # Print message print modified_message print ServerAddress # Close client socket ClientSocket.close() |
UDP server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # UDP server # include libraries import socket import sys # Create server ServerName = 'localhost' ServerPort = 1234 # Create server socket ServerAddress = (ServerName, ServerPort) ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4, UDP socket # Associate server port number with the socket ServerSocket.bind(ServerAddress) # anything sent to this port number will be received by this server print 'The server is ready to receive' # For continuous receival of messages while 1: message, ClientAddress = ServerSocket.recvfrom(2048) # receive the message from client along with source address print ClientAddress print ServerPort modifiedmessage = message.upper() # Capitalize the message ServerSocket.sendto(modifiedmessage,ClientAddress) # Attaches client address to the message and sends # Waits for other messages. |
Comments
Post a Comment