2023-2024
Fall Semester
Computer networks technology
socket programming
Outline:
What is a socket?
Blocking and non-blocking sockets
Client-server model
Communications modes
Socket programming with UDP
Socket programming with TCP
2
What is a Socket?
A socket is a communication end point.
• Is equivalent to a computer's network (hardware) interface.
• Allows a network application to "plug into" the network (not
physically, but metaphorically).
Is a network programming interface.
It is used for inter-process communication over the
network.
It is used by a process to communicate with a remote system
via a transport protocol.
It needs an IP address and a port number.
3
What is a Socket?
Sockets are popularly used in client/server
computing.
Provides two major types of services:
Connection-oriented
Connectionless
4
Sockets
process sends/receives messages to/from its socket
socket analogous to door
• sending process shoves message out door
• sending process relies on transport infrastructure on other side of
door to deliver message to socket at receiving process
• two sockets involved: one on each side
application application
socket controlled by
process process app developer
transport transport
network network controlled
link
by OS
link Internet
physical physical
5
goal: learn how to build client/server applications that
communicate using sockets
socket: door between application process and end-end-
transport protocol
application application
socket controlled by
process process app developer
transport transport
network network controlled
link
by OS
link Internet
physical physical
6
Operations on a Socket
Socket works very similar to a file
• open() socket() -- open a socket
• read() -- read from a socket (analogous to receive data)
• write() -- write to a socket (analogous to send data)
• close() -- close the socket
7
Where does Socket fit in the Network Stack?
8
Blocking and Non-blocking Sockets
By default read() and write() operations are
blocking
Function does not return until the operation is complete
read() blocks until there is some data available in the
receive buffer
When does write() block?
When the send buffer is full
9
Blocking and Non-blocking Sockets
Non-blocking read() and write() return immediately
read()
If there is some data in receive buffer, read() succeeds
and returns the amount of data read
If the receive buffer is empty, read() returns the ERROR
code
write()
If there is some space available in the send buffer,
write()succeeds and returns the amount of data written
If the send buffer is full, write() returns the ERROR code
10
Client-Server Model
11
Two traditional modes of communication
Connection-oriented Communication
Establish a logical or physical connection before exchanging data
Connectionless Communication
Start exchanging data without any prior arrangements between
endpoints
12
Socket programming with UDP
UDP: no “connection” between client and server:
no handshaking before sending data
sender explicitly attaches IP destination address and port # to each packet
receiver extracts sender IP address and port# from received packet
UDP: transmitted data may be lost or received out-of-
order
Application viewpoint:
UDP provides unreliable transfer of groups of bytes
(“datagrams”) between client and server processes
13
Connection-Oriented Services
Implemented on TCP
An end-to-end connection is established before data
exchange can happen.
Data bytes are delivered in sequence.
• Delivery of data is guaranteed.
Connection is terminated when finished.
There are two modes:
• Iterative (synchronous)
• Concurrent (asynchronous)
14
Connection less Services
Implemented on UDP
No connection is required before data transfer.
Data bytes may be missing or delivered out-
of-order.
There are two modes:
Iterative (synchronous)
Concurrent (asynchronous)
15
Socket Programming
To use a socket, one needs a structure to hold
address and its associated port number
information.
A generic socket format:
(address family, address in the family)
Another name for family is domain.
Struct sockaddr {
sa_family_t sa_family; /* address family */
char sa_data[14]; /* socket address */
}
16
Socket Types
17
Example 1:Client/Server Connectionless
It is implemented on UDP.
One server (iterative), multiple clients.
The server echoes back requests from
clients, one client request at a time.
A client sends user request to server and
displays response received from server.
18
Server Algorithm (connectionless -UDP)
A. Create a socket.
B. Bind to a predefined address for the service
desired.
C. Wait for a datagram to arrive from a client.
D. Send response back to originating client.
E. Return to C. for next client.
19
Client Algorithm (connectionless-UDP)
A. Create a socket.
B. Send a datagram to server.
C. Wait for response from server.
D. Return to B. for more datagrams.
E. Close the socket when no more datagram to
send.
20
Connectionless: Functions Used
21
UDP Client/Server Functions
22
Application Example:
1. client reads a line of characters (data) from its keyboard
and sends data to server
2. server receives the data and converts characters to
uppercase
3. server sends modified data to client
4. client receives modified data and displays line on its
screen
23
server (running on serverIP) client
create socket:
create socket, port= x: clientSocket =
serverSocket = socket(AF_INET,SOCK_DGRAM)
socket(AF_INET,SOCK_DGRAM)
Create datagram with serverIP address
And port=x; send datagram via
read datagram from clientSocket
serverSocket
write reply to
serverSocket read datagram from
specifying clientSocket
client address,
port number close
clientSocket
24
Python UDPClient
include Python’s socket library from socket import *
serverName = 'hostname'
serverPort = 12000
create UDP socket clientSocket = socket(AF_INET,
SOCK_DGRAM)
get user keyboard input message = input('Input lowercase sentence:')
attach server name, port to message; send into socket clientSocket.sendto(message.encode(),
(serverName, serverPort))
read reply data (bytes) from socket modifiedMessage, serverAddress =
clientSocket.recvfrom(2048)
print out received string and close socket print(modifiedMessage.decode())
clientSocket.close()
25
Note: this code update (2023) to Python 3
Python UDPServer
from socket import *
serverPort = 12000
create UDP socket serverSocket = socket(AF_INET, SOCK_DGRAM)
bind socket to local port number 12000 serverSocket.bind(('', serverPort))
print('The server is ready to receive')
loop forever while True:
Read from UDP socket into message, getting message, clientAddress = serverSocket.recvfrom(2048)
client’s address (client IP and port)
modifiedMessage = message.decode().upper()
send upper case string back to this client serverSocket.sendto(modifiedMessage.encode(),
clientAddress)
26
Note: this code update (2023) to Python 3
Client must contact server when contacted by client, server
server process must first be running TCP creates new socket for server
server must have created socket process to communicate with that
(door) that welcomes client’s particular client
contact • allows server to talk with multiple
Client contacts server by: clients
Creating TCP socket, specifying IP • client source port # and IP address used
address, port number of server to distinguish clients (more in Chap 3)
process
when client creates socket: client TCP Application viewpoint
establishes connection to server TCP provides reliable, in-order
TCP byte-stream transfer (“pipe”)
between client and server
processes
27
Server Algorithm (connection-oriented (TCP))
A. Create a socket.
B. Bind to a predefined address for the service desired.
C. Place the socket in passive mode.
D. Accept the next connection request from a client.
E. Read a request, process the request, and send back the
results.
F. Close the connection when done with a client.
G. Return to D. for next client.
28
Client Algorithm (connection-oriented (TCP))
A. Create a socket.
B. Connect the socket to the desired server.
C. Send a request and wait for the response.
D. Repeat C. until done.
E. Notify server of intention to terminate.
May close R/W end either separately or together at
the same time.
F. Close the socket (connection) when done.
29
Connection-oriented: Functions Used
30
TCP Client/Server functions
31
Client-Server Model - APIs
Connection-oriented protocol (TCP-suite)
Create a socket
Assign IP addr/Port # to the socket
Establish a queue for connections
32
Application Example:
1. client reads a line of characters (data) from its keyboard
and sends data to server
2. server receives the data and converts characters to
uppercase
3. server sends modified data to client
4. client receives modified data and displays line on its
screen
33
server (running on hostid) client
create socket,
port=x, for incoming
request:
serverSocket = socket()
wait for incoming create socket,
connection request
TCP connect to hostid, port=x
connectionSocket = connection setup clientSocket = socket()
serverSocket.accept()
send request using
read request from clientSocket
connectionSocket
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
34 clientSocket
Python TCPClient
from socket import *
serverName = 'servername'
serverPort = 12000
create TCP socket for server, clientSocket = socket(AF_INET, SOCK_STREAM)
remote port 12000
clientSocket.connect((serverName,serverPort))
sentence = input('Input lowercase sentence:')
clientSocket.send(sentence.encode())
No need to attach server name, port modifiedSentence = clientSocket.recv(1024)
print ('From Server:', modifiedSentence.decode())
clientSocket.close()
35
Note: this code update (2023) to Python 3
Example app: TCP server
Python TCPServer
from socket import *
serverPort = 12000
create TCP welcoming socket serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
server begins listening for
incoming TCP requests
serverSocket.listen(1)
print('The server is ready to receive')
loop forever while True:
server waits on accept() for incoming connectionSocket, addr = serverSocket.accept()
requests, new socket created on return
read bytes from socket (but sentence = connectionSocket.recv(1024).decode()
not address as in UDP) capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence.
encode())
close connection to this client (but not connectionSocket.close()
36 welcoming socket)
Note: this code update (2023) to Python 3
Socket programming: waiting for multiple events
sometimes a program must wait for one of several events to happen, e.g.,:
wait for either (i) a reply from another end of the socket, or (ii) timeout: timer
wait for replies from several different open sockets: select(), multithreading
timeouts are used extensively in networking
using timeouts with Python socket:
receive a message
socket() connect() send() settimeout() recv() …
timeout
handle
timeout
…
37
How Python socket.settimeout() works?
timer starts! no packet arrives in 30 secs timeout
s.settimeout(30) s.recv() interrupt s.recv() &
raise timeout exception
receive a message no packet arrives in 10 secs
timer starts! & timer stop! timer starts! timeout
s.settimeout(10) s.recv() s.recv() interrupt s.recv() &
raise timeout exception
Set a timeout on all future socket operations of that specific socket!
38
Python try-except block
Execute a block of code, and handle “exceptions” that may occur when executing that block of code
try:
Executing this try code block may cause exception(s) to catch. If an exception
<do something> is raised, execution jumps from jumps directly into except code block
except <exception>:
this except code block is only executed if an <exception> occurred in the try
<handle the exception> code block (note: except block is required with a try block)
39
Socket programming: socket timeouts
Toy Example:
- A shepherd boy tends his master’s sheep. Python TCPServer (Villagers)
- If he sees a wolf, he can send a message to
villagers for help using a TCP socket. from socket import *
- The boy found it fun to connect to the server serverPort = 12000
without sending any messages. But the villagers serverSocket = socket(AF_INET,SOCK_STREAM)
don’t think so.
- And they decided that if the boy connects to serverSocket.bind(('',serverPort))
the server and doesn’t send the wolf location serverSocket.listen(1)
within 10 seconds for three times, they will stop counter = 0
listening to him forever and ever.
while counter < 3:
set a 10-seconds timeout on connectionSocket, addr = serverSocket.accept()
all future socket operations connectionSocket.settimeout(10)
try:
timer starts when recv() is called and will wolf_location = connectionSocket.recv(1024).decode()
send_hunter(wolf_location) # a villager function
raise timeout exception if there is no connectionSocket.send('hunter sent')
message within 10 seconds.
except timeout:
catch socket timeout exception counter += 1
connectionSocket.close()
40
How to remove settimeout()?
Use settimeout(None). settimeout(0) will result in
changing the socket to non-blocking mode.
41