Network Programming

You might also like

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

Python – threading module

➢ provides much more powerful, high-level support for threads than the thread
module
➢ The threading module has the Thread class that used to create thread.
➢ The methods provided by the Thread class are as follows :−
▪ start() − The start() method starts a thread by calling the run method.
▪ join([time]) − The join() waits for threads to terminate.
➢ Creating Thread Using Threading Module
• To create a new thread, we create an object of Thread class.

t=threading.Thread(target=function_name, args=(arguments))
• It takes following arguments:
• target: the function to be executed by thread
• args: the arguments to be passed to the target function
• Once you have created the new Thread subclass, you can create an instance of
it and then start a new thread by invoking the start().
• To start a thread, we use start method of Thread class. t.start()
• Once the threads start, the current program (you can think of it like a main
thread) also keeps on executing. In order to stop execution of current program
until a thread is complete, we use join method. t.join()
• Once, it is finished, the remaining statements of current program are executed.
Dr. Elhossiny Ibrahim 0 4th year: network programming
Python – threading module
Example 1
import threading # calling the threading module
import time # for printing and giving delay in our functions
# Define a function for the thread with the name (print_time) and define two arguments
(the name of the thread and delay)
def print_time(threadName,delay):
count = 0 # create a counter and initialize it with 0
while count < 3: # make a loop and inside it provide a delay (sec) to be
time.sleep(delay) # able to show the thread execution because the
count += 1 # execution is fast and it difficult to see it without delay
print(threadName,"-----------",time.ctime()) #check the thread running
# Create two threads (t1 and t2) which is an objects of thread class :
t1=threading.Thread(target=print_time, args=("Thread 1",1))
t2=threading.Thread(target=print_time, args=("Thread 2",2))
# starting thread 1
t1.start()
# starting thread 2 Thread 1 ----------- Sat Mar 26 13:47:43 2022
t2.start() Thread 2 ----------- Sat Mar 26 13:47:44 2022
# wait until thread 1 is completely executed Thread 1 ----------- Sat Mar 26 13:47:44 2022
t1.join() Thread 1 ----------- Sat Mar 26 13:47:45 2022
Thread 2 ----------- Sat Mar 26 13:47:46 2022
# wait until thread 2 is completely executed Thread 2 ----------- Sat Mar 26 13:47:48 2022
t2.join() done
print("done")
Dr. Elhossiny Ibrahim 1 4th year: network programming
Join Function Effect

With join
Thread 1 ----------- Mon Mar 13 19:19:45 2023
Thread 2 ----------- Mon Mar 13 19:19:46 2023
Thread 1 ----------- Mon Mar 13 19:19:46 2023
Thread 1 ----------- Mon Mar 13 19:19:47 2023
Thread 2 ----------- Mon Mar 13 19:19:48 2023
Thread 2 ----------- Mon Mar 13 19:19:50 2023
done

Without join
done
Thread 1 ----------- Mon Mar 13 19:20:09 2023
Thread 2 ----------- Mon Mar 13 19:20:10 2023
Thread 1 ----------- Mon Mar 13 19:20:10 2023
Thread 1 ----------- Mon Mar 13 19:20:11 2023
Thread 2 ----------- Mon Mar 13 19:20:12 2023
Thread 2 ----------- Mon Mar 13 19:20:14 2023
Dr. Elhossiny Ibrahim 2 4th year: network programming
Python – threading module
Example 2
# importing the threading module
import threading
def print_cube(num): # function to print cube of given num
print("Cube: {}".format(num * num * num))
def print_square(num): # function to print square of given num
print("Square: {}".format(num * num))
# creating thread
# puts comma in args when it is only one argument.
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
t1.start() # starting thread 1
t2.start() # starting thread 2
# wait until thread 1 is completely executed
Square: 100
t1.join() Cube: 1000
# wait until thread 2 is completely executed Done!
t2.join()
# both threads completely executed
print("Done!")

Dr. Elhossiny Ibrahim 3 4th year: network programming


concurrent chat program (server-side)

import threading
import socket
host = '127.0.0.1’
port = 59000
server =socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
aliases = []
def broadcast(message):
for client in clients:
client.send(message)

Dr. Elhossiny Ibrahim 4 4th year: network programming


concurrent chat program (server-side)
# Function to handle clients'connections
def handle_client(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
alias = aliases[index]
broadcast(f'{alias} has left the chat room!'.encode('utf-8'))
aliases.remove(alias)
break

Dr. Elhossiny Ibrahim 5 4th year: network programming


concurrent chat program (server-side)

# Main function to receive the clients connection


def receive():
while True:
print('Server is running and listening ...’)
client, address = server.accept()
print(f'connection is established with {str(address)}’)
client.send('alias?'.encode('utf-8’))
alias = client.recv(1024)
aliases.append(alias)
clients.append(client)
print(f'The alias of this client is {alias}'.encode('utf-8’))
broadcast(f'{alias} has connected to the chat room'.encode('utf-8’))
client.send('you are now connected!'.encode('utf-8’))
thread = threading.Thread(target=handle_client, args=(client,))
thread.start()
if __name__ == "__main__": receive()

Dr. Elhossiny Ibrahim 6 4th year: network programming


concurrent chat program
(client-side)
import threading
import socket
alias = input('Choose an alias >>> ‘)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 59000))
def client_receive():
while True:
try:
message = client.recv(1024).decode('utf-8’)
if message == "alias?":
client.send(alias.encode('utf-8’))
else:
print(message)
except:
print('Error!’)
client.close()
break

Dr. Elhossiny Ibrahim 7 4th year: network programming


concurrent chat program
(client-side)
def client_send():
while True:
message = f'{alias}: {input("")}’
client.send(message.encode('utf-8’))
receive_thread =threading.Thread(target=client_receive)
receive_thread.start()
send_thread = threading.Thread(target=client_send)send_thread.start()

Dr. Elhossiny Ibrahim 8 4th year: network programming

You might also like