-
Notifications
You must be signed in to change notification settings - Fork 17
/
server.py
61 lines (42 loc) · 1.76 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
import socket
import threading
class Server:
def __init__(self):
self.start_server()
def start_server(self):
self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = int(input('Enter port to run the server on --> '))
self.clients = []
self.s.bind((host,port))
self.s.listen(100)
print('Running on host: '+str(host))
print('Running on port: '+str(port))
self.username_lookup = {}
while True:
c, addr = self.s.accept()
username = c.recv(1024).decode()
print('New connection. Username: '+str(username))
self.broadcast('New person joined the room. Username: '+username)
self.username_lookup[c] = username
self.clients.append(c)
threading.Thread(target=self.handle_client,args=(c,addr,)).start()
def broadcast(self,msg):
for connection in self.clients:
connection.send(msg.encode())
def handle_client(self,c,addr):
while True:
try:
msg = c.recv(1024)
except:
c.shutdown(socket.SHUT_RDWR)
self.clients.remove(c)
print(str(self.username_lookup[c])+' left the room.')
self.broadcast(str(self.username_lookup[c])+' has left the room.')
break
if msg.decode() != '':
print('New message: '+str(msg.decode()))
for connection in self.clients:
if connection != c:
connection.send(msg)
server = Server()