Implementation
UDP Sockets
What is Sockets?
Sockets are the endpoints of a bidirectional
communications channel. Sockets may communicate within a process, between
processes on the same machine, or between processes on different continents.
Sockets may be implemented over a number of different
channel types: Unix domain sockets, TCP, UDP, and so on.
The socket library provides specific classes for handling the common
transports as well as a generic interface for handling the rest. Sockets have
their own vocabulary −Sr.No. Term & Description
Domain
The family of protocols that is used as the transport
mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX,
PF_X25, and so on.
type
The type of communications between the two endpoints,
typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for
connectionless protocols.
protocol
Typically zero, this may be used to identify a variant
of a protocol within a domain and type.
hostname
The identifier of a network interface −
A string, which can be a host name, a dotted-quad
address, or an
IPV6 address in colon (and possibly dot) notation
A string
"<broadcast>", which specifies an
INADDR_BROADCAST
address.
A zero-length string, which specifies INADDR_ANY, or
An Integer, interpreted as a binary address in host
byte order.
5
port
Each server listens for clients calling on one or more
ports. A port may be a Fixnum port number, a string containing a port number,
or the name of a service.
A Simple Server
To write Internet servers, we use
the socket function available in socket module to create a socket object. A socket
object is then used to call other functions to setup a socket server.
A Simple Client
Let us write a very simple client program which opens
a connection to a given port 12345 and given host. This is very simple to
create a socket client using Python's socket module function.
Udp
server.py
import socket
UDP_IP =
"127.0.0.1"
UDP_PORT = 5005
sock =
socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP,
UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer
size is 1024 bytes
print ("received message:",
data,"from", addr)
Udp
Client.py
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind(('', 54312))
sock.sendto(MESSAGE.encode('ascii'), (UDP_IP, UDP_PORT))
Output:
UDP server up and listening
Message from Client:b"Hello UDP Server"
Client IP Address:("127.0.0.1", 51696)
Message from Server
b"Hello UDP Client"