Week-9 LDQ: 1. Socket Programming ? Ans
Week-9 LDQ: 1. Socket Programming ? Ans
1. Socket Programming ?
Ans:
They are the real backbones behind web browsing. In simpler terms, there
is a server and a client.
Ans: The primary socket API functions and methods in this module are:
• socket()
• .bind()
• .listen()
• .accept()
• .connect()
• .connect_ex()
• .send()
• .recv()
• .close()
3. Why should you use TCP?
The server listens on a specific port for incoming connections from clients.
When a client connects, the server reads the data sent by the client, echoes
it back to the client, and then closes the connection. Here's an example im-
plementation of an echo server in Python:
Example:
import socket
HOST = '' # The server's hostname or IP address
s.bind((HOST, PORT))
s.listen()
with conn:
print(f'Connected by {addr}')
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
The above code listens on port 5000 for incoming connections. When a
connection is established, it reads data from the connection using the
recv() method, and echoes it back to the client using the sendall() method.
The connection is closed when the client sends an empty message.
Example:
import socket
s.connect((HOST, PORT))
s.sendall(message.encode())
data = s.recv(1024)
print(f'Received: {data.decode()}’)
The above code connects to the server at localhost on port 5000. It prompts
the user to enter a message to send to the server, and sends it using the
sendall() method. The client then waits for a response from the server using
the recv() method, and prints the response to the console.
Ans: The left-hand column represents the server. On the right-hand side is
the client.
Starting in the top left-hand column, note the API calls the server makes to
setup a “listening” socket:
• socket()
• bind()
• listen()
• accept()
A listening socket does just what it sounds like. It listens for connections
from clients.
When a client connects, the server calls accept() to accept, or complete, the
connection.
The client calls connect() to establish a connection to the server and initi-
ate the three- way handshake. The handshake step is important since it en-
sures that each side of the connection is reachable in the network, in other
words that the client can reach the server and vice-versa. It may be that
only one host, client or server, can reach the other.
At the bottom, the client and server close() their respective sockets.