-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
53 lines (39 loc) · 1.35 KB
/
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import threading
import socket
host='127.0.0.1'#local host
port=55555
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((host,port))
server.listen()
clients=[]
nickNames=[]
def broadCast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message=client.recv(1024)
broadCast(message)
except:
index=client.index(client)
client.remove(client)
nickname=nickNames[index]
broadCast(f'{nickname} left the chat'.encode('ascii'))
nickNames.remove(nickname)
break
def receive():
while True:
client,address=server.accept()
#print("connected with {(address)}")
client.send('NICK'.encode('ascii'))
nickname=client.recv(1024).decode('ascii')
nickNames.append(nickname)
clients.append(client)
print(f'Nick name of the client is {nickname}')
broadCast(f'{nickname} joined the chat'.encode('ascii'))
client.send('Connected to the server!!'.encode('ascii'))
thread=threading.Thread(target=handle,args=(client,))
thread.start()
print("server is listing .....")
receive()