-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_class.py
86 lines (68 loc) · 2.64 KB
/
server_class.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
import socket
import os
import threading
import argparse
class Server(threading.Thread):
def __init__(self, host, port):
super().__init__()
self.connections = []
self.host = host
self.port = port
def run(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.host, self.port))
sock.listen(1)
print('Listening at:', sock.getsockopt(1, socket.SOL_SOCKET))
while True:
# Accept new connection
sc, sockname = sock.accept()
print('Accepted a new connection from {} to {}'.format(sc.getpeername(), sc.getsockname()))
# Create new thread
server_socket = ServerSocket(sc, sockname, self)
# Start new thread
server_socket.start()
# Add thread to active connections
self.connections.append(server_socket)
print('Ready to receive messages from', sc.getpeername())
def broadcast(self, message, source):
for connection in self.connections:
connection.send(message)
class ServerSocket(threading.Thread):
def __init__(self, sc, sockname, server):
super().__init__()
self.sc = sc
self.sockname = sockname
self.server = server
def run(self):
while True:
message = self.sc.recv(1024).decode('ascii')
if message:
print('{} says {!r}'.format(self.sockname, message))
self.server.broadcast(message, self.sockname)
else:
# Client has closed the socket, exit the thread
print('{} has closed the connection'.format(self.sockname))
self.sc.close()
server.remove_connection(self)
return
def send(self, message):
self.sc.sendall(message.encode('ascii'))
def exit(server):
while True:
ipt = input('')
if ipt == 'q':
print('Closing all connections...')
for connection in server.connections:
connection.sc.close()
print('Shutting down the server...')
os._exit(0)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Chatroom Server')
parser.add_argument('-p', metavar='PORT', type=int, default=1060,
help='TCP port (default 1060)')
args = parser.parse_args() # Create and start server thread
server = Server('127.0.0.1', args.p)
server.start()
exit = threading.Thread(target = exit, args = (server,))
exit.start()