-
Notifications
You must be signed in to change notification settings - Fork 1
/
a.py
52 lines (45 loc) · 1.59 KB
/
a.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
import socket
import threading
connections = []
total_connections = 0
class Client(threading.Thread):
def __init__(self, socket, address, id, name, signal):
threading.Thread.__init__(self)
self.socket = socket
self.address = address
self.id = id
self.name = name
self.signal = signal
def __str__(self):
return str(self.id) + " " + str(self.address)
def run(self):
while self.signal:
try:
data = self.socket.recv(8000)
except:
print("Client " + str(self.address) + " has disconnected")
self.signal = False
connections.remove(self)
break
if data != "":
print("ID " + str(self.id) + ": " + str(data.decode("utf-8")))
for client in connections:
if client.id != self.id:
client.socket.sendall(data)
def newConnections(socket):
while True:
sock, address = socket.accept()
global total_connections
connections.append(Client(sock, address, total_connections, "Name", True))
connections[len(connections) - 1].start()
print("New connection at ID " + str(connections[len(connections) - 1]))
total_connections += 1
def main():
host = 'localhost'
port = 4488
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(5)
newConnectionsThread = threading.Thread(target = newConnections, args = (sock,))
newConnectionsThread.start()
main()