Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import struct
- import threading
- import queue
- import time
- import datetime
- class SocketClientThread(threading.Thread):
- def __init__(self, cmd_q=None, reply_q=None):
- super(SocketClientThread, self).__init__()
- self.reply_q = reply_q or queue.Queue()
- self.alive = threading.Event()
- self.alive.set()
- self.socket = None
- def run(self):
- while self.alive.isSet():
- try:
- self._handle_RECEIVE()
- except queue.Empty as e:
- continue
- def join(self, timeout=None):
- self.alive.clear()
- threading.Thread.join(self, timeout)
- def _handle_CONNECT(self):
- self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.socket.connect(('192.168.101.222', 2605))
- def _handle_RECEIVE(self):
- data = self.socket.recv(1024)
- self.reply_q.put(data)
- TCP_IP = '192.168.101.222'
- TCP_PORT = 2605
- BUFFER_SIZE = 1024
- NUM_MESSAGES = 2
- t = SocketClientThread()
- t._handle_CONNECT()
- ClientIPAddress = t.socket.getsockname()[0]
- ClientSocketNum = t.socket.getsockname()[1]
- t.start()
- for x in range(0, NUM_MESSAGES):
- 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|"
- TCPHEADER = len(MESSAGE).to_bytes(2, byteorder='big')
- LOGMESSAGE = str(TCPHEADER) + MESSAGE
- #1 here
- print(LOGMESSAGE + '\n')
- t.socket.send(TCPHEADER)
- t.socket.send(bytes(MESSAGE, 'utf-8'))
- if not t.reply_q.empty():
- resp = t.reply_q.get()
- print(str(resp) + '\n')
- #2 here
- while not t.reply_q.empty():
- resp = t.reply_q.get()
- print(str(resp) + '\n')
- t.socket.shutdown(socket.SHUT_RD)
- t.socket.shutdown(socket.SHUT_WR)
- t.socket.close()
- t.join()
- #TRAILER_RECORD = str(datetime.datetime.today().strftime('%m%d%Y')) + "|" + str(time.strftime('%H%M%S'))
- #with open(FILENAME, 'a') as out:
- # out.write(TRAILER_RECORD)
- # 1
- # with open(FILENAME, 'a') as out:
- # out.write(LOGMESSAGE + '\n')
- # 2
- # with open(FILENAME, 'a') as out:
- # out.write(str(resp) + '\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement