Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Python File Transfer and Chat using

TCP Sockets

CS307: Systems Practicum Lecture-4


Prof. Varun Dutt, IIT Mandi 23rd Feb 2023

Lecture - 4, 8th Feb 2024


Socket programming
Sockets are endpoints in a bidirectional communication channel that establishes communication
between a server and one or more clients. In this case, we create a socket on either end and allow a
client to communicate with other clients via the server. The socket on the server side is associated with
a hardware port on the server. Every client with a socket on the same port can communicate with the
server socket.

Multi-Threading
A thread is a subprocess that executes a set of commands independently of other threads. As a result,
whenever a user connects to the server, a distinct thread is generated for that user, and communication
from the server to the client occurs through individual threads based on socket objects produced for the
sake of each client's identification.
To set up file transfer or chat room, we'll need two scripts. One to keep the server running, and one for
each client to use in order to connect to the server.
What is TCP?
TCP stands for Transmission Control Protocol. It is a communication protocol that is designed for end-to-end
data transmission over a network. TCP is basically the ” standard” communication protocol for data
transmission over the Internet.

It is a highly efficient and reliable communication protocol as it uses a three-way handshake to connect the client
and the server. It is a process that requires both the client and the server to exchange synchronization (SYN) and
acknowledge (ACK) packets before the data transfer takes place.

Some of the features of the TCP are as follows:

1. It provides end-to-end communication.


2. It is a connection-oriented protocol.
3. It provides error-checking and recovery mechanisms.
TCP Procedure
TCP is a highly efficient and reliable communication
protocol as it uses a three-way handshake to connect the
client and the server. It is a process that requires both the
client and the server to exchange synchronization (SYN) and
acknowledge (ACK) packets before the data transfer takes
place.
Project Structure

The project is divided into two files:

1. server.py
2. client.py

The client.py contains the code, used to read a text file and send its data to the server. While the server.py file
receives the data sent by the client and save it to a text file.
File Transfer : Server
The server performs the following functions:

1. Create a TCP socket.


2. Bind the IP address and PORT to the server socket.
3. Listening for the clients.
4. Accept the connection from the client.
5. Receive the filename from the client and create a text file.
6. Send a response back to the client.
7. Receive the text data from the client.
8. Write (save) the data into the text file.
9. Send a response message back to the client.
10. Close the text file.
11. Close the connection.
Server.py
File Transfer : Client
The client performs the following functions:

1. Create a TCP socket for the client.


2. Connect to the server.
3. Read the data from the text file.
4. Send the filename to the server.
5. Receive the response from the server.
6. Send the text file data to the server.
7. Receive the response from the server.
8. Close the file.
9. Close the connection.
Client.py
Client.py
Chat application: Server Side Script
The server-side script will attempt to open a socket and bind it to the user-specified IP address and port (windows
users might have to make an exception for the specified port number in their firewall settings, or can rather use a
port that is already open). The script will then remain open and accept connection requests, appending the
appropriate socket objects to a list to maintain track of active connections. Each time a user connects, a new
thread is established for that user. The server waits for a message in each thread and sends it to the other users
that are currently on the chat. If the server finds an issue while attempting to receive a message from a certain
thread, that thread will be terminated.
Usage

● In a local area network, server can be set up by selecting any computer on the network as a server node
and using that device's private IP address as the server IP address.
● For example, if a local area network includes 99 nodes with private IP addresses ranging from
192.168.1.2 to 192.168.1.100, any of the 99 nodes can act as a server, and the remaining nodes can
connect to the server node using the server's private IP address.
● It is critical to select a port that is not currently in use. For example, the default port for ssh is 22 while the
default port for HTTP protocols is 80. Hence, ideally, these two ports should not be used or changed to
make them available for use.
● However, if the server is to be used outside of a local network, the public IP address must be used.
● In circumstances where a node from a local network (not the router) wishes to host the server, port
forwarding would be required.
Server Side Script
# Python program to implement server side of chat room.
import socket
import select
import sys
from _thread import *

"""The first argument AF_INET is the address domain of the socket. This is used when we have an
Internet Domain with any two hosts The second argument is the type of socket. SOCK_STREAM means
that data or characters are read in a continuous flow."""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# checks whether sufficient arguments have been provided


if len(sys.argv) != 3:
print ("Correct usage: script, IP address, port number")
exit()

# takes the first argument from command prompt as IP address


IP_address = str(sys.argv[1])
Server Side Script
# takes second argument from command prompt as port number
Port = int(sys.argv[2])

"""
binds the server to an entered IP address and at the specified port number. The client must be
aware of these parameters
"""

server.bind((IP_address, Port))

"""
listens for 100 active connections. This number can be increased as per convenience.
"""

server.listen(100)

list_of_clients = []
Server Side Script
def clientthread(conn, addr):
# sends a message to the client whose user object is conn
conn.send("Welcome to this chat room!")
while True:
try:
message = conn.recv(2048)
if message:
"""prints the message and address of the
user who just sent the message on the server
terminal"""
print ("<" + addr[0] + "> " + message)
# Calls broadcast function to send message to all
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send, conn)
else:
"""message may have no content if the connection
is broken, in this case we remove the connection"""
remove(conn)
except:
continue
Server Side Script
"""Using the below function, we broadcast the message to all clients whose object is not the
same as the one sending the message """

def broadcast(message, connection):

for clients in list_of_clients:

if clients!=connection:

try:
clients.send(message)

except:
clients.close()

# if the link is broken, we remove the client


remove(clients)
Server Side Script
"""The following function simply removes the object from the list that was created at the
beginning of the program"""
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)

while True:
"""Accepts a connection request and stores two parameters, conn which is a socket object for
that user, and addr which contains the IP address of the client that just connected"""
conn, addr = server.accept()
"""Maintains a list of clients for ease of broadcasting a message to all available people in
the chatroom"""
list_of_clients.append(conn)
# prints the address of the user that just connected
print (addr[0] + " connected")
# creates and individual thread for every user that connects
start_new_thread(clientthread,(conn,addr))

conn.close()
server.close()
Client Side Script
# Python program to implement client side of chat room.
import socket
import select
import sys

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

if len(sys.argv) != 3:
print ("Correct usage: script, IP address, port number")
exit()

IP_address = str(sys.argv[1])

Port = int(sys.argv[2])

server.connect((IP_address, Port))
Client Side Script
while True:
# maintains a list of possible input streams
sockets_list = [sys.stdin, server]
""" There are two possible input situations. Either the user wants to give manual input to send
to other people,or the server is sending a message to be printed on the screen. Select returns
from sockets_list, the stream that is reader for input. So for example, if the server wants to
send a message, then the if condition will hold true below.If the user wants to send a message,
the else condition will evaluate as true"""
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print (message)
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()
Output
$ python chat_server.py $python client.py
<192.168.59.24> Hello! Welcome to this chatroom!
<192.168.60.147> hey there! Hello!
<192.168.59.24> Are you receiving my <You>Hello!
messages? <192.168.60.147> hey there!
<192.168.60.147> yes I am!
Are you receiving my messages?
<You>Are you receiving my messages?
<192.168.60.47> yes I am!
References
● https://www.geeksforgeeks.org/simple-chat-room-using-python/
● https://idiotdeveloper.com/file-transfer-using-tcp-socket-in-python3/

You might also like