Lecture 4
Lecture 4
Lecture 4
TCP Sockets
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.
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:
● 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)
"""
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 """
if clients!=connection:
try:
clients.send(message)
except:
clients.close()
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
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/