-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
91 lines (48 loc) · 1.62 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
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
81
82
83
84
85
86
87
88
89
90
91
import socket
<<<<<<< HEAD
import threading
PORT = 5000
SERVER = socket.gethostbyname(socket.gethostname())
ADDRESS = (SERVER, PORT)
=======
import threading
PORT = 5000
SERVER = socket.gethostbyname(socket.gethostname())
ADDRESS = (SERVER, PORT)
>>>>>>> b0d886abb6412d04f36032a62fe0973be9acd998
FORMAT = "utf-8"
clients, names = [], []
<<<<<<< HEAD
=======
>>>>>>> b0d886abb6412d04f36032a62fe0973be9acd998
server = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server.bind(ADDRESS)
def startChat():
print("SERVER STARTED at " + SERVER)
print("WAITING FOR CONNECTIONS:")
server.listen()
while True:
conn, addr = server.accept()
conn.send("NAME".encode(FORMAT))
name = conn.recv(1024).decode(FORMAT)
names.append(name)
clients.append(conn)
print(f"Name is :{name}")
broadcastMessage(f"{name} has joined the chat!".encode(FORMAT))
conn.send('[CONNECTED]'.encode(FORMAT))
thread = threading.Thread(target = handle,
args = (conn, addr))
thread.start()
print(f"active connections {threading.activeCount()-1}")
def handle(conn, addr):
print(f"new connection {addr}")
connected = True
while connected:
message = conn.recv(1024)
broadcastMessage(message)
conn.close()
def broadcastMessage(message):
for client in clients:
client.send(message)
startChat()