-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbus.py
54 lines (44 loc) · 1.82 KB
/
bus.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
from twisted.internet import reactor, protocol
class DropLink(protocol.Protocol):
def __init__(self, factory):
self.factory = factory
self.name = None
def connectionMade(self):
self.factory.clients.append(self)
print("New client connected to bus backbone.")
def connectionLost(self, reason):
self.factory.clients.remove(self)
print("Client disconnected.")
def dataReceived(self, data):
message = data.decode().strip()
if not self.name:
self.name = message
print(f"{self.name} connected to bus.")
else:
if message.startswith("@"):
recipient, private_message = message[1:].split(":", 1)
self.sendPrivateMessage(recipient, private_message)
else:
print(f"{self.name}: {message}")
self.broadcastMessage(f"{self.name}: {message}")
def sendPrivateMessage(self, recipient, message):
for client in self.factory.clients:
if client.name == recipient:
client.transport.write(f"(Private) {self.name}: {message}\n".encode())
break
else:
self.transport.write(f"Error: User {recipient} not found.\n".encode())
def broadcastMessage(self, message):
for client in self.factory.clients:
if client != self:
client.transport.write(f"{message}\n".encode())
class BusBackbone(protocol.Factory):
def __init__(self):
self.clients = []
def buildProtocol(self, addr):
return DropLink(self)
if __name__ == "__main__":
reactor.listenTCP(8000, BusBackbone())
print("Bus server started.")
print("Enter your name as first message to register. To send a message to a particular username use '@username: message'.")
reactor.run()