Working with UDP Sockets
Well, in the socket's basic tutorial you might have had a confusion that we define socket as:
S = socket.socket(socket_family, socket_type, protocol = 0)
But, in the last tutorial covering TCP sockets we defined TCP socket by merely writing S=socket.socket()
, that is without providing the socket_family and the socket_type. If we do not mention the socket_family and socket_type, then by default it is TCP
. So, if we want to create a UDP socket than we have to specify socket_family and socket_type explicitly.
For UDP socket we define:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
and, if you explicitly want to define a TCP socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Simple UDP Server program
This is the udpserver.py
script:
#!usr/bin/python
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # For UDP
udp_host = socket.gethostname() # Host IP
udp_port = 12345 # specified port to connect
#print type(sock) ============> 'type' can be used to see type
# of any variable ('sock' here)
sock.bind((udp_host,udp_port))
while True:
print "Waiting for client..."
data,addr = sock.recvfrom(1024) #receive data from client
print "Received Messages:",data," from",addr
Output of the above script is as follows. Keep it running and than fire up the client.py
module.
Simple UDP Client
This is the udpclient.py
script:
#!usr/bin/python
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # For UDP
udp_host = socket.gethostname() # Host IP
udp_port = 12345 # specified port to connect
msg = "Hello Python!"
print "UDP target IP:", udp_host
print "UDP target Port:", udp_port
sock.sendto(msg,(udp_host,udp_port)) # Sending message to UDP server
Our udpserver.py
is up and running, so now we try to run the udpclient.py
script,
And here is what happened to our server after the client sends the request:
Flow Diagram of the Program
So in this tutorial and the last one, we have learnt how to setup a successful Client-Server connection using both TCP socket and UDP sockets.