5 6183896532710854099
5 6183896532710854099
Submitted By:
1. Dibbyo Roy Roll:28
2. Abdullah Ashik Roll:32
Submitted To:
1. Dr. Md. Abdur Razzaque
2. Dr. Md. Mamun or Rashid
3. Dr. Muhhamad Ibrahim
4. Mr. Md. Redwan Ahmed Rizvee
1
1 Introduction
Socket programming is a way of enabling communication between
processes running on different networked computers. It allows pro-
cesses to communicate with each other, either on the same machine
or across a network, by using sockets, which are communication
endpoints.
1.1 Objectives
The objective of socket programming is to facilitate communica-
tion between processes running on different networked computers or
within the same computer. It enables data exchange, allowing pro-
grams to send and receive information over a network using sockets
as communication endpoints. Socket programming aims to estab-
lish reliable and efficient communication channels between client and
server applications, facilitating tasks such as file transfer, remote ex-
ecution, real-time messaging, and distributed computing.
2 Theory
Socket programming is based on the concept of sockets, which are
communication endpoints that allow processes to communicate with
each other over a network. Here’s a brief explanation of the theory
behind socket programming:
Sockets:
Sockets are software abstractions representing communication
endpoints in a network. Each socket is identified by an IP address
and a port number, allowing processes to establish connections and
communicate with each other. Client-Server Model:
Socket programming typically follows the client-server model,
where one program (the server) listens for incoming connections,
and another program (the client) initiates connections to the server.
The server binds a socket to a specific IP address and port, listens
for incoming connections, and accepts them. The client connects
to the server’s IP address and port, establishing a communication
channel. Communication Protocols:
TCP sockets provide reliable, connection-oriented communica-
tion, ensuring data integrity and in-order delivery. UDP sockets
2
provide connectionless communication, offering lower overhead but
without reliability guarantees. Data Exchange:
Once a connection is established between client and server, they
can exchange data using the socket’s send() and recv() functions (for
TCP) or sendto() and recvfrom() functions (for UDP). TCP sock-
ets transmit data as a continuous stream, ensuring reliability and
in-order delivery. UDP sockets transmit data as individual data-
grams, which may arrive out of order or be lost. Error Handling
and Exception Handling:
Socket programming involves error handling mechanisms to deal
with network-related errors, such as connection failures or data
transmission errors. Exception handling is used to gracefully han-
dle exceptions that may occur during socket operations, ensuring the
robustness of the communication system. Socket programming en-
ables a wide range of networked applications, including web servers,
chat applications, file transfer protocols, and more. It provides a
flexible and powerful mechanism for processes to communicate and
collaborate over a network.
3 Methodology
3.1 Server
A server is a computer or system that provides resources, data, or
services to other computers or clients over a network. On the server
side when we turn it on it will wait for any client request. If it
gets any request then it will establish a connection. After setting
up the connection, it receives a query corresponding to which file
client requested .In this section Our task was Client sends Small
letter .Server receives it and converts it to Capital letter and checks
whether a number is prime or not and sends the result to client.We
also implemented a Bank server .When a client requests for checking
balance,cash deposit, cash withdrawal server does the operation and
send back the result to the client .It can be said that server accepts
all valid requests and rejects the requests that are invalid.
3
3.2 Client
A client is a computer or system that requests and uses the resources,
data, or services provided by a server. Here our client side is any
web browser .We will enter the IP address of our server and the port
number. Then a request will be sent from client to the server. In our
lab task we had to implement an ATM booth machine as a client.
We will see some answers to the query that the server provided.
3.3 Problem A
Establishing a TCP connection in between a server process, running
on host A and a client process, running on host B and then perform
some operation by the server process requested by the client and
send responses from the server.
1. Small letter to capital conversion for a line of text
2. Checking whether a number is prime or not and also have to
check whether the number
SERVER
for conversion small letter to capitall letter
#(a) 1. Capital letter to Small letter conversion for a line of text. This pro
import socket
import threading
HEADER = 64
PORT = 5050
FORMAT = ’utf-8’
DISCONNECTMESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
print (SERVER)
4
def handleClient(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msgLength = conn.recv(HEADER).decode(FORMAT)
if msgLength:
msgLength = int(msgLength)
msg = conn.recv(msgLength).decode(FORMAT)
print("Message received: ", msg)
if msg == DISCONNECTMESSAGE:
connected = False
print(f"[{addr}] {msg.upper()}")
conn.send(response.encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handleClient, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
start()
5
Client
import socket
HEADER = 64
PORT = 5050
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
while True:
msg = input("Enter message: ")
send(msg)
print(client.recv(2048).decode(FORMAT))
if msg == DISCONNECT_MESSAGE:
break
import socket
import threading
6
import utils
HEADER = 64
PORT = 5050
FORMAT = ’utf-8’
DISCONNECTMESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
print (SERVER)
connected = True
while connected:
msgLength = conn.recv(HEADER).decode(FORMAT)
if msgLength:
msgLength = int(msgLength)
msg = conn.recv(msgLength).decode(FORMAT)
print("Message received: ", msg)
if msg == DISCONNECTMESSAGE:
connected = False
isPalidrome = utils.isPalidrome(msg)
msg = int(msg)
conn.send(response.encode(FORMAT))
7
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handleClient, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
start()
import socket
HEADER = 64
PORT = 5050
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
8
client.send(message)
while True:
msg = input("Enter message: ")
send(msg)
print(client.recv(2048).decode(FORMAT))
if msg == DISCONNECT_MESSAGE:
break
3.4 Problem B
Create a TCP connection and design and implement a non-idempotent
operation between bank server and ATM booth (client).
import socket
import threading
import utils
import random
HEADER = 64
PORT = 5050
FORMAT = ’utf-8’
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
print(SERVER)
9
def handleClient(conn, addr):
global total_transactions, successful_transactions # Declare global varia
connected = True
while connected:
msgLength = conn.recv(HEADER).decode(FORMAT)
if msgLength:
msgLength = int(msgLength)
msg = conn.recv(msgLength).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
break
if utils.getName(int(msg[0]), int(msg[1:5])) == False:
str = "Invalid ID or Password\n"
conn.send(str.encode(FORMAT))
continue
name = utils.getName(int(msg[0]), int(msg[1:5]))
msgLength = conn.recv(HEADER).decode(FORMAT)
if msgLength:
msgLength = int(msgLength)
msg = conn.recv(msgLength).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
break
if msg[5] == "1":
10
str = f"Your balance is {utils.getBalance(int(msg[0]), int
str += f"Total transactions: {total_transactions}\n"
str += f"Success rate: {successful_transactions/total_tran
str += f"Error rate: {(total_transactions-successful_trans
conn.send(str.encode(FORMAT))
conn.send(str.encode(FORMAT))
msgLength = conn.recv(HEADER).decode(FORMAT)
if msgLength:
msgLength = int(msgLength)
msg = conn.recv(msgLength).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
break
if rand > 5:
utils.deposit(int(msg[0]), int(msg[1:5]), int(msg[
successful_transactions += 1 # Increment successf
str = f"Your balance is {utils.getBalance(int(msg[
str += f"Successful transactions: {successful_tran
str += f"Total transactions: {total_transactions}\
str += f"Success rate: {successful_transactions/to
str += f"Error rate: {(total_transactions-successf
conn.send(str.encode(FORMAT))
else:
str = "Transaction failed\n"
str += f"Your balance is {utils.getBalance(int(msg
str += "Please try again\n"
str += f"Total transactions: {total_transactions}\
str += f"Success rate: {successful_transactions/to
str += f"Error rate: {(total_transactions-successf
conn.send(str.encode(FORMAT))
11
conn.send(str.encode(FORMAT))
msgLength = conn.recv(HEADER).decode(FORMAT)
if msgLength:
msgLength = int(msgLength)
msg = conn.recv(msgLength).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
break
if rand > 5:
utils.withdraw(int(msg[0]), int(msg[1:5]), int(msg
successful_transactions += 1 # Increment successf
str = f"Your balance is {utils.getBalance(int(msg[
str += f"Successful transactions: {successful_tran
str += f"Total transactions: {total_transactions}\
str += f"Success rate: {successful_transactions/to
str += f"Error rate: {(total_transactions-successf
conn.send(str.encode(FORMAT))
else:
str = "Transaction failed\n"
str += f"Your balance is {utils.getBalance(int(msg
str += "Please try again\n"
str += f"Total transactions: {total_transactions}\
str += f"Success rate: {successful_transactions/to
str += f"Error rate: {(total_transactions-successf
conn.send(str.encode(FORMAT))
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handleClient, args=(conn, addr))
thread.start()
12
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
start()
import socket
HEADER = 64
PORT = 5050
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
while True:
id = input("Enter ID: ")
password = input("Enter Password: ")
send(id, password)
print(client.recv(2048).decode(FORMAT))
13
choice = input("Enter choice: ")
send(id, password, choice)
if choice == "1":
print(client.recv(2048).decode(FORMAT))
4 Experimental Result
4.1 Problem A
Server :
Server takes a string or an integer from the client. It converts the
string to an upper case string and send it back to the client. On the
other hand, it check the integer if its a prime or not and send the
result to the client.
14
Prime)
4.2 Problem B
This is for ATM Machine Problem we set four option for client
Checking balance , withdraw , deposit and exit if client choose exit
he will be exit from connection otherwise we have shown her/his
15
successful transaction.
5 Experience
1. We had a wonderful experience with how servers and clients work
in real life.
16
2. Experienced how socket programming work and establish con-
nection between client and server.
References
1. Socket programming in python. GeeksforGeeks, jun 20 2017.
[Online; accessed 2023-01-25].
2. Pankaj. Python socket programming - Server, client example.
DigitalOcean, aug 3 2022. [Online;accessed 2023-01-25].
3. Real Python. Socket programming in python (guide). Real
Python, feb 21 2022. [Online; accessed 2023-01-25].
17