-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
81 lines (72 loc) · 2.46 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
import socket,threading
host = ''
port = 23
clients = []
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
clients.append(client)
print("{} connected".format(address))
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (clients,client,address)).start()
def listenToClient(self,clients ,client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
# Set the response to echo back the recieved data
response = data
print("Recived data is {}".format(data))
for x in clients:
x.send(response)
#client.send(response)
else:
raise error('Client disconnected')
except:
print("{} CLOSE".format(address))
clients.remove(client)
client.close()
return False
if __name__ == "__main__":
ThreadedServer(host,port).listen()
'''
def listening(clients,client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
# Set the response to echo back the recieved data
response = data
print("Recived data is {}".format(data))
#client.send(response)
broadcast(clients, response)
return response
else:
raise error('Client disconnected')
except:
client.close()
def broadcast(clients, response):
for client in clients:
client.send(response)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
while True:
client, address = sock.accept()
clients.append(client)
print("{} connected".format(address))
client.settimeout(60)
response = listening(clients, client, address)
#broadcast(clients, response)
'''