Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.44 KB | None | 0 0
  1. from twisted.internet.protocol import Protocol, Factory
  2. from twisted.internet import reactor
  3.  
  4. class Client(Protocol):
  5. ip: str = None
  6. login: str = None
  7. factory: 'Chat'
  8. unique_login: bool = True
  9.  
  10. def __init__(self, factory):
  11. """
  12. Инициализация фабрики клиента
  13. :param factory:
  14. """
  15. self.factory = factory
  16.  
  17. def connectionMade(self):
  18. """
  19. Обработчик подключения нового клиента
  20. """
  21.  
  22. self.ip = self.transport.getHost().host
  23.  
  24. def dataReceived(self, data: bytes):
  25. """
  26. Обработчик нового сообщения от клиента
  27. :param data:
  28. """
  29. message = 'login:' + data.decode().replace('\n', '')
  30. message = message.replace('login:', '')
  31.  
  32. if self.login is None:
  33. login = message
  34.  
  35. if login not in self.factory.logins:
  36. """
  37. Уникальный логин
  38. """
  39. self.login = login
  40. self.factory.clients.append(self)
  41. self.factory.logins.append(self.login)
  42. self.unique_login = True
  43.  
  44. print(f"Client connected: {self.login} : {self.ip}")
  45.  
  46. self.transport.write("Welcome to the chat v0.2\n***************************\n".encode())
  47. for i in self.factory.history:
  48. self.transport.write(i.encode())
  49.  
  50. self.factory.notify_all_users(f'Client connected: {self.login}')
  51. self.factory.history.append(f'Client connected: {self.login}\n')
  52.  
  53. else:
  54. self.transport.write("Error this login already exists!\nEnter new login >>> ".encode())
  55. print('New client tried connect with existed login')
  56. else:
  57. server_message = f"{self.login}: {message}"
  58. self.factory.notify_all_users(server_message)
  59. self.factory.history.append(server_message + '\n')
  60. print(server_message)
  61.  
  62. def connectionLost(self, reason=None):
  63. """
  64. Обработчик отключения клиента
  65. :param reason:
  66. """
  67. if self.unique_login:
  68. self.factory.clients.remove(self)
  69. self.factory.logins.remove(self.login)
  70. print(f"Client disconnected:\n{self.login}:{self.ip}")
  71.  
  72.  
  73. class Chat(Factory):
  74. clients: list
  75. logins: list
  76. history: list
  77.  
  78. def __init__(self):
  79. """
  80. Инициализация сервера
  81. """
  82. self.clients = []
  83. self.logins = []
  84. self.history = []
  85. print("*" * 10, "\nStart server \nCompleted [OK]")
  86.  
  87. def startFactory(self):
  88. """
  89. Запуск процесса ожидания новых клиентов
  90. :return:
  91. """
  92. print("\n\nStart listening for the clients...")
  93.  
  94. def buildProtocol(self, addr):
  95. """
  96. Инициализация нового клиента
  97. :param addr:
  98. :return:
  99. """
  100. return Client(self)
  101.  
  102. def notify_all_users(self, data: str):
  103. """
  104. Отправка сообщений всем текущим пользователям
  105. :param data:
  106. :return:
  107. """
  108. for user in self.clients:
  109. user.transport.write(f"{data}\n".encode())
  110.  
  111.  
  112. if __name__ == '__main__':
  113. reactor.listenTCP(7410, Chat())
  114. reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement