-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
55 lines (41 loc) · 1.37 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
#!/usr/bin/python3
# coding=utf-8
import socket
import threading
class Server:
def __init__(self):
self.ip = socket.gethostbyname(socket.gethostname())
while 1:
try:
# self.port = int(input('Enter port number to run on --> '))
self.port = 8000
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((self.ip, self.port))
break
except:
print("Couldn't bind to that port")
self.connections = []
self.accept_connections()
def accept_connections(self):
self.s.listen(100)
print('Running on IP: ' + self.ip)
print('Running on port: ' + str(self.port))
while True:
c, addr = self.s.accept()
self.connections.append(c)
threading.Thread(target=self.handle_client, args=(c, addr,)).start()
def broadcast(self, sock, data):
for client in self.connections:
if client != self.s and client != sock:
try:
client.send(data)
except:
pass
def handle_client(self, c, addr):
while 1:
try:
data = c.recv(1024)
self.broadcast(c, data)
except socket.error:
c.close()
server = Server()