Advertisement
pegorino

jim

Jan 17th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. import json
  2. import socket
  3.  
  4.  
  5. class JIMMessage:
  6.     CODING = 'utf-8'
  7.     SIZE = 1024
  8.  
  9.     def __init__(self, sock):
  10.         self.sock = sock
  11.         self.msg = None
  12.  
  13.     def get(self):
  14.         try:
  15.             msg = self.sock.recv(self.SIZE)
  16.             self.msg = json.loads(msg.decode(self.CODING))
  17.         except socket.error:
  18.             print('Failed to get data')
  19.         finally:
  20.             return self.msg
  21.  
  22.     def send(self, message):
  23.         msg = json.dumps(message).encode(self.CODING)
  24.         try:
  25.             self.sock.send(msg)
  26.         except socket.error:
  27.             print('Failed to send data')
  28.  
  29.  
  30. if __name__ == '__main__':
  31.     host = 'localhost'
  32.     port = 7777
  33.  
  34.     testmessage = {'action': 'presense',
  35.                    'time': '',
  36.                    'type': 'text',
  37.                    'to': '#_test_chat_room',
  38.                    'from': '',
  39.                    'message': 'some test message',
  40.                    'encoding': 'utf-8',
  41.                    'user': {
  42.                        'account_name': 'USERNAME',
  43.                        'password': 'PASSWORD'
  44.                    }
  45.                    }
  46.  
  47.     with socket.socket() as sock:
  48.         sock.connect((host, port))
  49.  
  50.         # отправляет сообщение
  51.         sended = JIMMessage(sock)
  52.         sended.send(testmessage)
  53.  
  54.         # принимает сообщения
  55.         msg = JIMMessage(sock).get()
  56.         print(msg)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement