Advertisement
pegorino

client

Jan 11th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.38 KB | None | 0 0
  1. import socket
  2. import time
  3. import sys
  4.  
  5. from cmd_utils import cmd_client
  6. from usefull_utils import parse
  7.  
  8. from log_config import client_log
  9.  
  10. host = 'localhost'
  11. port = 7777
  12.  
  13. CODING = 'utf-8'
  14. ACTION = 'presence'
  15. TIME = time.time()
  16. USERNAME = 'Evgeny'
  17. PASSWORD = 123456
  18. TEST_MESSAGE = 'Hello, server! (default)'
  19. TEMPLATE = {'action': ACTION,
  20.             'time': TIME,
  21.             'type': 'text',
  22.             'to': '#_test_chat_room',
  23.             'from': '',
  24.             'message': TEST_MESSAGE,
  25.             'encoding': CODING,
  26.             'user': {
  27.                 'account_name': USERNAME,
  28.                 'password': PASSWORD
  29.             }
  30.             }
  31.  
  32.  
  33. @client_log
  34. def send_request(sock, data):
  35.     '''
  36.    отправляет запрос на сервер
  37.    :param sock:
  38.    :param data:
  39.    :return:
  40.    '''
  41.     if type(sock) == socket.socket:
  42.         # if isinstance(sock, socket.socket):
  43.         try:
  44.             sock.send(data)
  45.             return True
  46.         except socket.error:
  47.             print('Failed to send data!')
  48.     else:
  49.         print('Trying to send data to not socket object!')
  50.  
  51.  
  52. @client_log
  53. def get_response(sock):
  54.     '''
  55.    получает ответ от сервера
  56.    :param sock:
  57.    :return:
  58.    '''
  59.     if type(sock) == socket.socket:
  60.         try:
  61.             data = sock.recv(1024)
  62.             return data
  63.         except socket.error:
  64.             print('Failed to receive data!')
  65.     else:
  66.         print('Trying to recieve data from not socket object!')
  67.  
  68.  
  69. # здесь код
  70. def client_action(params):
  71.     flag = params[0]
  72.  
  73.     host = params[1]
  74.     port = int(params[2])
  75.  
  76.     print('flag {}'.format(params[0]), end=' / ')
  77.  
  78.     with socket.socket() as sock:
  79.         sock.connect((host, port))
  80.  
  81.         # TODO
  82.         # вывести в консоль клиента его имя (уникальный индетификатор), чтобы контролировать от кого приходит запрос на сервере
  83.         print('client\'s port', sock.getsockname()[1])
  84.  
  85.         if flag == '-w':
  86.             while True:
  87.  
  88.                 text = input('type text (<exit> for exit): ')
  89.                 if text == 'exit':
  90.                     break
  91.  
  92.                 message = text
  93.                 temp = TEMPLATE
  94.                 temp['from'] = sock.getsockname()[1]
  95.                 temp['message'] = message
  96.                 btemp = parse(temp)
  97.  
  98.                 send_request(sock, btemp)
  99.  
  100.         if flag == '-r':
  101.             try:
  102.                 while True:
  103.                     m = get_response(sock)
  104.                     mess = parse(m)
  105.  
  106.                     t_local = time.localtime(mess['time'])
  107.                     t = time.strftime('%d.%m.%Y - %H:%M:%S', t_local)
  108.  
  109.                     print('client {} ({}) send message: {}'.format(mess['message from'], t, mess['text']))
  110.  
  111.             # ??? не работает на ctrl+C, выключаю клиента ctrl+break
  112.             except KeyboardInterrupt:
  113.                 print('Leaved chat!')
  114.  
  115.  
  116. if __name__ == '__main__':
  117.  
  118.     # запуск на чтение
  119.     # client_action(['-r', host, port, 'some text'])
  120.  
  121.     # запуск на отправку сообщений
  122.     # client_action(['-w', host, port, 'some text'])
  123.  
  124.     # запуск из коммандной строки
  125.     client_action(cmd_client(sys.argv))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement