Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. import socket
  2. import struct
  3. import threading
  4. import queue
  5. import time
  6. import datetime
  7.  
  8.  
  9. class SocketClientThread(threading.Thread):
  10. def __init__(self, cmd_q=None, reply_q=None):
  11. super(SocketClientThread, self).__init__()
  12. self.reply_q = reply_q or queue.Queue()
  13. self.alive = threading.Event()
  14. self.alive.set()
  15. self.socket = None
  16.  
  17. def run(self):
  18. while self.alive.isSet():
  19. try:
  20. self._handle_RECEIVE()
  21. except queue.Empty as e:
  22. continue
  23.  
  24. def join(self, timeout=None):
  25. self.alive.clear()
  26. threading.Thread.join(self, timeout)
  27.  
  28. def _handle_CONNECT(self):
  29. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  30. self.socket.connect(('192.168.101.222', 2605))
  31.  
  32. def _handle_RECEIVE(self):
  33. data = self.socket.recv(1024)
  34. self.reply_q.put(data)
  35.  
  36.  
  37. TCP_IP = '192.168.101.222'
  38. TCP_PORT = 2605
  39. BUFFER_SIZE = 1024
  40. NUM_MESSAGES = 2
  41.  
  42. t = SocketClientThread()
  43. t._handle_CONNECT()
  44. ClientIPAddress = t.socket.getsockname()[0]
  45. ClientSocketNum = t.socket.getsockname()[1]
  46. t.start()
  47.  
  48. for x in range(0, NUM_MESSAGES):
  49. MESSAGE = "REQ|" + str(int(round(time.time() * 1000))) + "|" + str(x) + "|DanielEarly|211037|0|" + str(ClientIPAddress) + "|" + str(ClientSocketNum) + "|123|" + str(TCP_IP) + "|" + str(TCP_PORT) + "|TestData|1|"
  50. TCPHEADER = len(MESSAGE).to_bytes(2, byteorder='big')
  51. LOGMESSAGE = str(TCPHEADER) + MESSAGE
  52. #1 here
  53. print(LOGMESSAGE + '\n')
  54. t.socket.send(TCPHEADER)
  55. t.socket.send(bytes(MESSAGE, 'utf-8'))
  56. if not t.reply_q.empty():
  57. resp = t.reply_q.get()
  58. print(str(resp) + '\n')
  59. #2 here
  60.  
  61. while not t.reply_q.empty():
  62. resp = t.reply_q.get()
  63. print(str(resp) + '\n')
  64.  
  65. t.socket.shutdown(socket.SHUT_RD)
  66. t.socket.shutdown(socket.SHUT_WR)
  67. t.socket.close()
  68. t.join()
  69.  
  70. #TRAILER_RECORD = str(datetime.datetime.today().strftime('%m%d%Y')) + "|" + str(time.strftime('%H%M%S'))
  71. #with open(FILENAME, 'a') as out:
  72. # out.write(TRAILER_RECORD)
  73.  
  74. # 1
  75. # with open(FILENAME, 'a') as out:
  76. # out.write(LOGMESSAGE + '\n')
  77.  
  78. # 2
  79. # with open(FILENAME, 'a') as out:
  80. # out.write(str(resp) + '\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement