-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathP32_Mutithreading_Server.py
38 lines (33 loc) · 1.11 KB
/
P32_Mutithreading_Server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#This program illustrates the client-server model using multithreading.
#Multiole clients can connect to server and each time a client connects a corresponding
#thread is created for handling client requests
import socket
import os
from _thread import *
ServerSocket = socket.socket()
host = '127.0.0.1'
port = 1233
ThreadCount = 0
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Waitiing for a Connection..')
ServerSocket.listen(5)
#Function for handling requests by a thread
def threaded_client(connection):
connection.send(str.encode('Welcome to the Server\n'))
while True:
data = connection.recv(2048)
reply = 'Server Says: ' + data.decode('utf-8')
if not data:
break
connection.sendall(str.encode(reply))
connection.close()
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()