-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
73 lines (59 loc) · 2.64 KB
/
server.py
File metadata and controls
73 lines (59 loc) · 2.64 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# PORTFOLIO 1 - s341848 - Izen Asmar Nasar
# TCP server
import socket,threading,sys,time,argparse
# parser that checks if necessary arguments are provided
argParser = argparse.ArgumentParser(description='Start the chat server and listen for incoming connections. Example: server.py 4242')
argParser.add_argument('port', type=int, help='The port the server is running on (Integers only).')
args = argParser.parse_args()
port = args.port
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('localhost', port))
serverSocket.listen() # listen for connections
clients = [] # list of clients
clientNames = [] # list of the clients' names
# broadcast a given message from a client to the other clients
def messageAll(message, client):
for i in clients:
# dont send the message back to the original sender
if i is not client:
i.send(message)
# chatting inbetween the clients(host and bots)
def handle_client(client):
while True:
try:
message = client.recv(1024)
msg = message.decode().split(": ")
if(msg[1] == "SHUTDOWN"):
time.sleep(1)
print("Disconnecting clients")
for i in clients:
i.close()
print("Server status: Down\nStopped listening to connections...")
exit()
else:
time.sleep(0.5)
messageAll(message, client) #send to all bots
except:
index = clients.index(client)
clients.remove(client)
client.close()
name = clientNames[index]
messageAll(f'{name} has disconnected from the chat room!'.encode('utf-8'), client)
print(f'{name} disconnected from the chat room')
clientNames.remove(name)
break
# set server status and connect incoming clients to the server(chat room)
def receive():
print('\nServer status: Running\nListening to connections...\n')
while True:
client, address = serverSocket.accept() # accept connection
client.send('name?'.encode('utf-8'))
name = client.recv(1024).decode('utf-8')
clientNames.append(name)
clients.append(client)
print(f'Successfully established a connection with {name} {str(address)}')
messageAll(f'{name} has connected to the chat room'.encode('utf-8'), client)
client.send('You are now connected to the chat room!'.encode('utf-8'))
thread = threading.Thread(target=handle_client, args=(client,))
thread.start()
receive()