-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer Code.py
More file actions
80 lines (64 loc) · 2.15 KB
/
Server Code.py
File metadata and controls
80 lines (64 loc) · 2.15 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import socket
import threading
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket is succesfully created..!')
port = 5555
Host='127.0.0.1'
serversocket.bind((Host, port))
print('Sucessfully binded..! ')
serversocket.listen(5)
print('Started listening...')
clients=[]
#Thread is created
def Handle(client,username):
while True:
try:
#server is receiving the data from client
data=client.recv(1024).decode('utf-8')
receiver=client.recv(1024).decode('utf-8')
sending(data,receiver,client,username)
except:
# if the client left, remove the name and the data.
index = clients.index(client)
clients.remove(client)
client.close()
print('{} left the conversation..!'.format(username))
clients.remove(username)
break
#Server is sending the data to the client
def sending(data,receiver,client,username):
try:
index = clients.index(receiver)
RecvClient=clients[index+1]
RecvClient.sendall(data.encode('utf-8'))
except:
data=('The entered name is not present at the moment. The online users are: '.encode('ascii'))
client.sendall(data)
length=len(clients)
i=0
for x in range(length):
try:
usernamesList=('{} \n'.format(clients[x+i]))
client.sendall(usernamesList.encode('utf-8'))
i=i+1
except:
break
#waiting for the connections to accept
while True:
client,Addr = serversocket.accept()
print("connected with {}".format(str(Addr)))
client.send('Username'.encode('utf-8'))
username=client.recv(1024).decode('utf-8')
clients.append(username)
clients.append(client)
length=len(clients)
i=0
for x in range(length):
try:
usernamesList=('{} \n'.format(clients[x+i]))
client.sendall(usernamesList.encode('utf-8'))
i=i+1
except:
break
#creating a thread
threading._start_new_thread(Handle, (client,username))