-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
94 lines (80 loc) · 2.82 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
92
93
94
"""
Server side: it simultaneously handle multiple clients
and broadcast when a new client joins or a client
sends a message.
"""
import socket
import _thread as thread
import time
import sys
#this is too keep all the newly joined connections!
all_client_connections = []
def now():
"""
returns the time of day
"""
return time.ctime(time.time())
def handleClient(connection: socket.socket, addr):
"""
a client handler function
"""
username = connection.recv(2048).decode()
sender = connection.getpeername()
#this is where we broadcast everyone that a new client has joined
### Write your code here ###
# append this to the list for broadcast
all_client_connections.append(connection)
# create a message to inform all other clients
joinMessage = "just joined the chat"
# that a new client has just joined.
broadcast(joinMessage, sender, username)
### Your code ends here ###
while True:
message = connection.recv(2048).decode()
print (now() + " " + str(addr) + "# ", message)
if (message == "exit" or not message):
### Write your code here ###
quitMessage = "just left the chat"
#broadcast this message to the others
broadcast(quitMessage, sender, username)
### Your code ends here ###
break
else:
broadcast(message, sender, username)
connection.close()
all_client_connections.remove(connection)
def broadcast(message, sender, username):
print ("Broadcasting")
### Write your code here ###
for connection in all_client_connections:
if connection.getpeername() != sender:
connection.sendall(f"[{username}]: {message}".encode())
### Your code ends here ###
def main():
"""
creates a server socket, listens for new connections,
and spawns a new thread whenever a new connection join
"""
serverPort = 12000
serverName = '0.0.0.0' #socket.gethostbyname(socket.gethostname())
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = (serverName, serverPort)
try:
# Use the bind function wisely!
serverSocket.bind(addr)
except socket.error as e:
print("Bind failed. Error : Guru Meditation #%s" % e)
sys.exit()
serverSocket.listen(10)
print ('The server is ready to receive')
while True:
### Write your code here ###
connectionSocket, addr = serverSocket.accept() # accept a connection
print(f"[ACTIVE CONNECTIONS] {thread._count() + 1}")
### You code ends here ###
print('Server connected by ', addr)
print('at ', now())
thread.start_new_thread(handleClient, (connectionSocket,addr))
serverSocket.close()
if __name__ == '__main__':
main()