-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
43 lines (27 loc) · 857 Bytes
/
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
import socket
import threading
UDP_IP_ADDRESS = socket.gethostname()
UDP_PORT_NO = 6789
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
Alamat=[]
Nama=[]
def broadcast(message):
for a in Alamat:
serverSock.sendto(message,a)
def Terima():
while True:
print("waiting for client")
msg, addr = serverSock.recvfrom(1024)
msg=msg.decode('utf-8')
if addr in Alamat:
index=Alamat.index(addr)
editedMSG=f'{Nama[index]}: {msg}'
broadcast(editedMSG.encode('utf-8'))
else:
Alamat.append(addr)
Nama.append(msg)
welcomeMSG=f'{msg} has joined the chat'.encode('utf-8')
broadcast(welcomeMSG)
t=threading.Thread(target=Terima)
t.start()