def sendString (self, message): #printOut ('SOCKETCLASS sendString: sending %s bytes to %s' % # (len(message),self.retAddress)) try: self.sock.sendto (message, self.retAddress ) printOut ("SOCKETCLASS sendString: completed sending message") except: printOut ("SOCKETCLASS sendString: exception sending message")
def sendString (self, message): if (self.conn != None): try: #printOut ('TCPSOCKETCLASS sendString: sending %s bytes to %s' % # (len(message),self.retAddress)) size = self.conn.send ( message ) if (size == 0): # We lost the connection self.conn = None printOut ("TCPSOCKETCLASS sendString: lost connection") else: #printOut ("TCPSOCKETCLASS sendString: message sent") pass except: printOut ("TCPSOCKETCLASS sendString: exception sending message")
def __init__(self, ipAddr, portNo, server = False, cmdQueue=None, bufSize=1024): self.ipAddr = ipAddr self.portNo = portNo self.address = (self.ipAddr, self.portNo) self.server = server # Set up as server (true) or client (false) self.cmdQueue = cmdQueue self.bufSize = bufSize self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP self.threadFlag = True # Use to kill the serial port thread self.retAddress = (self.ipAddr, self.portNo) # Return addr of messages if (self.server): # Setup this instance as a server printOut ("SOCKETCLASS: Setting up as UDP server - binding") self.sock.bind ( self.address ) #printOut ("SOCKETCLASS: Setting up as UDP server - listening") #self.sock.listen (1) printOut ("SOCKETCLASS: Setting up as UDP server - complete") else: printOut ("SOCKETCLASS: Setting up as UDP client\n") #self.sock.connect ( (self.ipAddr, self.portNo) ) # endif if (cmdQueue is not None): # start the command thread and give it some time to start up self.serThread = threading.Thread ( group=None, target=self.receiveThread, name = "receiveThread" ) self. serThread.start() time.sleep (0.2) printOut ("SOCKETCLASS: Completed setting up thread\n")
def receiveThread(self): printOut ("SOCKETCLASS: starting receive thread") runFlag = self.threadFlag while (runFlag): data, address = self.sock.recvfrom(self.bufSize) self.retAddress = address self.cmdQueue.put(data) if (True): printOut ('SOCKETCLASS: Received %s bytes from address %s' % (len(data), self.retAddress)) runFlag = self.threadFlag # end while self.sock.close() printOut ("SOCKETCLASS: terminating receive thread" )
def main(self): with open(argv[-2]) as sourceFile: for line in sourceFile: self.sourceLines.append(line) dataDest = codecs.open(argv[-1], "w", "utf-8") switchCase = {"sprzedaż": self.sale_fun, "zakup": self.buy_fun} while self.check: action = self.sourceLines[self.count].strip() if action == "saldo": saldo = self.saldo_fun( int(self.sourceLines[self.count + 1]), self.sourceLines[self.count + 2].strip(), ) self.count += 3 elif action == "zakup" or action == "sprzedaż": switchCase[action]( self.sourceLines[self.count + 1].strip(), int(self.sourceLines[self.count + 2]), int(self.sourceLines[self.count + 3]), dataDest, ) self.count += 4 elif action == "stop": if len(argv) == 1: printOut(self.logs, dataDest) elif argv[1] == "saldo": saldo = self.saldo_fun(int(argv[2]), argv[3]) dataDest.write(str(saldo)) break elif argv[1] == "zakup": self.buy_fun(argv[2], int(argv[3]), int(argv[4]), dataDest) if not self.check: break printOut(self.logs, dataDest) elif argv[1] == "sprzedaż": self.sale_fun(argv[2], int(argv[3]), int(argv[4]), dataDest) if not self.check: break printOut(self.logs, dataDest) elif argv[1] == "konto": dataDest.write(str(saldo)) break elif argv[1] == "magazyn": for name in argv[2:-2]: if name in self.storehouse: dataDest.write("{}: {}\n".format( name, self.storehouse[name])) else: dataDest.write("{}: 0\n".format(name)) elif argv[1] == "przegląd": for index, log in enumerate(self.logs): if index >= int(argv[2]) and index <= int(argv[3]): if log == "stop": dataDest.write("{}\n".format(log)) break else: for log_element in log: dataDest.write("{}\n".format(log_element)) else: printOut(self.logs, dataDest) self.logs.append("stop") dataDest.write(self.logs[-1]) break else: dataDest.write( "Błędna nazwa operacji. Podano {}".format(action)) break
def killThread (self): self.threadFlag = False printOut ("SOCKETCLASS killThread: setting threadFlag false")
# killThread - stops the serial port thread ########################################################################### def killThread (self): self.threadFlag = False printOut ("SOCKETCLASS killThread: setting threadFlag false") # end # End class ############################################################################### if __name__ == "__main__": IPADDR = "127.0.0.1" PORTNO = 61432 printOut ("Getting instanceNo") sys.stdout.flush() instanceNo = sys.argv printOut ("instanceNo is %s\n" % (instanceNo)) inputQueue = Queue(400) sc = socketClass(IPADDR, PORTNO, inputQueue, 128) if (instanceNo == '1'): for i in range(0, 25): msg = inputQueue.get() printOut ("--> 1) RECEIVED - %s\n" % (msg)) sc.sendString ("--> 1) XMITTNG msg %d" % (i)) # end for elif (instanceNo == '2'):
def receiveThread(self): printOut ("TCPSOCKETCLASS: starting receive thread, waiting for accept") # Keep waiting for a connection as long as we're told not to abort while (self.threadFlag): self.conn = None printOut ("TCPSOCKETCLASS: waiting to accept connection") self.threadExec = True # Yep, the thread is executing try: #conn, addr = self.sock.accept(0) conn, addr = self.sock.accept() self.conn = conn printOut ("TCPSOCKETCLASS: accepted connection" ) except: time.sleep(1.0) # Keep waiting for data as long as we have a connection and # we're not told to abort while (self.conn != None and self.threadFlag): #data, address = self.sock.recvfrom(self.bufSize) #self.retAddress = address data = self.conn.recv(self.bufSize) self.cmdQueue.put(data) if (True): printOut ('TCPSOCKETCLASS: Received %s bytes from address %s' % (len(data), self.retAddress)) if (len(data) == 0): # We lost the connection printOut ('TCPSOCKETCLASS: connection lost') self.conn = None # end while # end while self.sock.close() self.threadExec = False # Thread now terminated printOut ("TCPSOCKETCLASS: receive thread terminated" )
def __init__(self, sockType, ipAddr, portNo, server = True, cmdQueue=None, bufSize=1024): self.sockType = sockType self.ipAddr = ipAddr self.portNo = portNo self.address = (self.ipAddr, self.portNo) self.server = server # Set up as server (true) or client (false) self.cmdQueue = cmdQueue self.bufSize = bufSize self.conn = None # The current socket connection self.threadFlag = True # Use to kill the serial port thread self.threadExec = False # Indicates if the thread is running self.retAddress = (self.ipAddr, self.portNo) # Return addr of messages if (self.sockType != TCP and self.sockType != UDP): printOut("SocketClass: ERROR unknown socket type (TCP, UDP)") raise ValueError('SocketClass: Socket Type neither TCP or UDP') # SOCK_STREAM for TCP, SOCK_DGRAM for UDP if (self.sockType == TCP): printOut ("SocketClass: Setting up socket for TCP") self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: printOut ("SocketClass: Setting up socket for UDP") self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #end if if (self.server): # Setup this instance as a server #printOut ("TCPSOCKETCLASS: Setting up as server - binding to %s" % ((self.address)) ) print("TCPSOCKETCLASS: Setting up as server - binding to ", self.address) self.sock.bind ( self.address ) printOut ("TCPSOCKETCLASS: Setting up as server - listening") self.sock.listen (1) printOut ("TCPSOCKETCLASS: Setting up as server - complete") else: printOut ("TCPSOCKETCLASS: Setting up as client\n") self.sock.connect ( (self.ipAddr, self.portNo) ) # endif if (cmdQueue is not None): # start the command thread and give it some time to start up self.serThread = threading.Thread ( group=None, target=self.receiveThread, name = "receiveThread" ) self. serThread.start() while ( not self.threadExec): time.sleep (0.1) # end if printOut ("TCPSOCKETCLASS: Completed setting up thread\n")
def close (self): printOut ("TCPSOCKETCLASS close: Waiting for thread to terminate") self.threadFlag = False while (self.threadExec): time.sleep (0.1) printOut ("TCPSOCKETCLASS close: Tthread terminated")
# End class ############################################################################### # TESTING ############################################################################### #sockType, ipAddr, portNo, server = True, cmdQueue=None, bufSize=1024): if __name__ == "__main__": IPADDR = "127.0.0.1" IPADDR = 'localhost' IPADDR = '' PORTNO = 61432 instanceNo = sys.argv printOut ("instanceNo is %s\n" % (instanceNo[1])) inputQueue = Queue(10) if (instanceNo[1] == 'S'): # Server sock = tcpSocketClass(TCP, IPADDR, PORTNO, True, inputQueue) for i in range(0, 25): time.sleep (3) try: msg = inputQueue.get_nowait() printOut ("--> 1) RECEIVED - %s\n" % (msg)) except: pass # end try sock.sendString ("Message %d" % (i))
count += 3 elif action == "zakup" or action == "sprzedaż": switchCase[action]( sourceLines[count + 1].strip(), int(sourceLines[count + 2]), int(sourceLines[count + 3]), saldo, check, logs, storehouse, dataDest, ) count += 4 elif action == "stop": if len(argv) == 1: printOut(logs, dataDest) elif argv[1] == "saldo": saldo = saldo_fun(int(argv[2]), argv[3], saldo, logs) dataDest.write(str(saldo)) break elif argv[1] == "zakup": buy_fun( argv[2], int(argv[3]), int(argv[4]), saldo, check, logs, storehouse, dataDest, )