-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerSide.py
More file actions
54 lines (45 loc) · 1.57 KB
/
Copy pathServerSide.py
File metadata and controls
54 lines (45 loc) · 1.57 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
import socket
from threading import Thread
USERNO=0
def AcceptConn():
while True:
Client, ClientAddr = SERVER.accept()
addresses[Client] = ClientAddr
Thread(target=HandleClient, args=(Client,)).start()
def HandleClient(Client):
global USERNO
Name = Client.recv(1024).decode("utf8")
USERNO=USERNO+1
Welcome = "Welcome {}! To exit chatroom, type [quit] anytime. Number of Users online: {}".format(Name,USERNO)
Client.send(bytes(Welcome,"utf8"))
Msg = "{} has joined the chat. Number of Users online: {}".format(Name,USERNO)
Broadcast(Msg, Name)
clients[Client] = Name
while True:
Msg = Client.recv(1024).decode("utf8")
if Msg != "[quit]":
Broadcast(Msg, Name, Name+": ")
else:
Client.close()
del clients[Client]
USERNO=USERNO-1
Broadcast("{} has left the chat. Number of Users online: {}".format(Name,USERNO),Name)
break
def Broadcast(Msg, Sender="", Prefix="") :
for s in clients:
if (Sender != "") and (clients[s] != Sender):
s.send(bytes(Prefix+Msg+"\n","utf8"))
elif (Sender != "") and (clients[s] == Sender):
s.send(bytes("You: "+Msg+"\n","utf8"))
clients={}
addresses={}
HOST = '127.0.0.1'
PORT = 12345
SERVER = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
SERVER.bind((HOST,PORT))
if __name__=="__main__":
SERVER.listen()
NEWTHREAD = Thread(target=AcceptConn)
NEWTHREAD.start()
NEWTHREAD.join()
SERVER.close()