def test_create_connection_success2(self): connection = self.getConnection() connection.close() self.listener.close() time.sleep(TIMEOUT) SomeProcess._connections.pop().close() self.assertEquals(self.accepts_started, self.accepts_ended) time.sleep(TIMEOUT)
def send_receive(self, httpMethod, endpointContext, payload): endpoint = '/stratos' + endpointContext connection = http.client.HTTPConnection('127.0.0.1','9763') headers = {"Content-type": "application/json", "Accept": "application/json"} connection.request(httpMethod,endpoint,payload,headers) response = connection.getresponse() print(response.status,response.reason) connection.close()
def send_receive(self, httpMethod, endpointContext, payload): endpoint = '/stratos' + endpointContext connection = http.client.HTTPConnection('127.0.0.1', '9763') headers = { "Content-type": "application/json", "Accept": "application/json" } connection.request(httpMethod, endpoint, payload, headers) response = connection.getresponse() print(response.status, response.reason) connection.close()
def Establish_Connection(database): connection = None try: connection = sqlite3.connect(database) cur = connection.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cur.fetchall()) except Error as e: print(e) finally: if connection: connection.close()
def test_create_connection_closed_patched(self): close_called = [] def close(): close_called.append(1) return _close() _close = self.listener.listener._listener.close self.listener.listener._listener.close = close connection = self.getConnection() time.sleep(TIMEOUT) SomeProcess._connections.pop().close() connection.close() self.listener.close() time.sleep(TIMEOUT) self.assertNotEquals(close_called, [])
def run(self): """ Run the thread, accepting connections and then listening on them until they are closed. Each message is a call into the function table. """ logger.debug("server listening on '%s'", self.pipe) while self._is_closed is False: logger.debug("server thread is about to create a server") ready = False # test to see if there is a connection waiting on the pipe if sys.platform == "win32": try: mpc_win32.WaitNamedPipe(self.server.address, self.LISTEN_TIMEOUT * 1000) ready = True except WindowsError as e: logger.debug("Error during WaitNamedPipe:", exc_info=True) if e.args[0] not in ( mpc_win32.ERROR_SEM_TIMEOUT, mpc_win32.ERROR_PIPE_BUSY, ): raise ready = False else: # can use select on osx and linux (rd, _, _) = select.select([self.server._listener._socket], [], [], self.LISTEN_TIMEOUT) ready = len(rd) > 0 if not ready: logger.debug("server thread could not create server") continue connection = None try: # connection waiting to be read, accept it logger.debug("server about to accept connection") connection = SafePickleConnection(self.server.accept()) logger.debug("server accepted connection") while self._is_closed is False: # test to see if there is data waiting on the connection has_data = connection.poll(self.LISTEN_TIMEOUT) # see if we need to stop the server if self._is_closed: return # If we timed out waiting for data, go back to sleep. if not has_data: continue # data coming over the connection is a tuple of (name, args, kwargs) (respond, func_name, args, kwargs) = pickle.loads(connection.recv()) logger.debug("server calling '%s(%s, %s)'" % (func_name, args, kwargs)) try: if func_name not in self._functions: logger.error( "unknown function call: '%s', expecting one of '%s'" % (func_name, self.list_functions())) raise ValueError("unknown function call: '%s'" % func_name) # grab the function from the function table func = self._functions[func_name] # execute the function on the main thread. It may do GUI work. result = self.engine.execute_in_main_thread( func, *args, **kwargs) # If the RPC server was stopped, don't bother trying to reply, the connection # will have been broken on the client side and this will avoid an error # on the server side when calling send. if self._SERVER_WAS_STOPPED != result: # if the client expects the results, send them along logger.debug("server got result '%s'" % result) if respond: connection.send(pickle.dumps(result)) except Exception as e: # if any of the above fails send the exception back to the client logger.error("got exception '%s'" % e) logger.debug(" traceback:\n%s" % traceback.format_exc()) if respond: connection.send(pickle.dumps(e)) except (EOFError, IOError): # let these errors go # just keep serving new connections pass finally: # It's possible we failed accepting, so the variable may not be defined. if connection is not None: logger.debug("server closing") connection.close() logger.debug("server closed") logger.debug("server thread shutting down")
playerData = {'move': mymove, 'sym': sym} connection.send(playerData) waitmess = connection.recv() updateboard = connection.recv() winstatus = connection.recv() if waitmess == "Invalid Entry, try again": print(updateboard) print(waitmess) valid = 1 else: print(updateboard) print(waitmess) break if newboard == "P1 Wins!" or newboard == "P2 Wins!" or newboard == 9: break if winstatus == "P1 Wins!" or winstatus == "P2 Wins!" or winstatus == 9: break #print(winstatus) print("Game Over") if newboard == "P1 Wins!" or newboard == "P2 Wins!": print(connection.recv()) print(newboard) if winstatus == "P1 Wins!" or winstatus == "P2 Wins!": print(connection.recv()) print(winstatus) if winstatus == 9 or newboard == 9: print(connection.recv()) print("CAT") connection.close()
def __exit__(self, exc_type, exc_val, exc_tb): connection.close()
def run(self): """ Run the thread, accepting connections and then listening on them until they are closed. Each message is a call into the function table. """ self._logger.debug("server listening on '%s'", self.pipe) while True: # test to see if there is a connection waiting on the pipe if sys.platform == "win32": # need to use win32 api for windows mpc_win32 = multiprocessing.connection.win32 try: mpc_win32.WaitNamedPipe(self.server.address, self.LISTEN_TIMEOUT*1000) ready = True except WindowsError, e: if e.args[0] not in (mpc_win32.ERROR_SEM_TIMEOUT, mpc_win32.ERROR_PIPE_BUSY): raise ready = False else: # can use select on osx and linux (rd, _, _) = select.select([self.server._listener._socket], [], [], self.LISTEN_TIMEOUT) ready = (len(rd) > 0) if not ready: # nothing ready, see if we need to stop the server, if not keep waiting if self._stop: break continue # connection waiting to be read, accept it connection = self.server.accept() self._logger.debug("server accepted connection") try: while True: # test to see if there is data waiting on the connection if not connection.poll(self.LISTEN_TIMEOUT): # no data waiting, see if we need to stop the server, if not keep waiting if self._stop: break continue # data coming over the connection is a tuple of (name, args, kwargs) (respond, func_name, args, kwargs) = pickle.loads(connection.recv()) self._logger.debug("server calling '%s(%s, %s)'" % (func_name, args, kwargs)) try: if func_name not in self._functions: self._logger.error("unknown function call: '%s'" % func_name) raise ValueError("unknown function call: '%s'" % func_name) # grab the function from the function table func = self._functions[func_name] # execute the function on the main thread. It may do GUI work. result = self.engine.execute_in_main_thread(func, *args, **kwargs) # if the client expects the results, send them along self._logger.debug("server got result '%s'" % result) if respond: connection.send(pickle.dumps(result)) except Exception as e: # if any of the above fails send the exception back to the client self._logger.error("got exception '%s'" % e) self._logger.debug(" traceback:\n%s" % traceback.format_exc()) if respond: connection.send(pickle.dumps(e)) except (EOFError, IOError): # let these errors go # just keep serving new connections pass finally: self._logger.debug("server closing") connection.close()
if Listener.has_pipe and 1: class CreateConnectionsTestPipe(CreateConnectionsTestIpv4): ListenerClass = Listener.PipeListener if Listener.has_unix: class CreateConnectionsTestUnix(CreateConnectionsTestIpv4): ListenerClass = Listener.UnixListener ##del CreateConnectionsTestIpv6, CreateConnectionsTestIpv4 if __name__ == '__main__': unittest.main(exit = False, verbosity = 1) if False: import sys time.sleep(0.1) # wait for threads to die print 'frames:', len(sys._current_frames().items()) print 'connections:', len(SomeProcess._connections) for connection in SomeProcess._connections: connection.close() time.sleep(5) # wait for threads to die for k in sorted(sys._current_frames()): f = sys._current_frames()[k] if k in startedThreads: print f.f_code.co_filename, print k, f.f_code.co_firstlineno else: print print 'frames:', len(sys._current_frames().items())