Exemplo n.º 1
0
def init_connection(server, sockets, clients, data_in, data_out, epoll):
    socket, address = server.accept()
    socket.setblocking(0)

    fd = socket.fileno()
    epoll.register(fd, select.EPOLLOUT | select.EPOLLIN | select.EPOLLET)
    sockets[fd] = socket
    clients.append(fd)
    data_in[fd] = b''

    light_message = light_pb2.LightsUpdateMessage()
    light_message.type = light_pb2.SET_LIGHTS
    for fixture in lights:
        light_message.lights.extend([fixture.to_message()])

    data_out[fd] = make_message(light_message, "light_update")

    global audio_url
    global audio_on
    if audio_on == True:
        audio_message = audio_pb2.AudioMessage()
        audio_message.type = audio_pb2.PLAY_AUDIO
        audio_message.url = audio_url
        data_out[fd] += make_message(audio_message, "audio")

    print("Accepted new client {:02d}".format(fd))
Exemplo n.º 2
0
 def __init__(self, socket, name="new"):
     socket.setblocking(0)
     self.socket = socket  # The socket that select() uses to communicate with
     # the client process. One client process exists per user
     self.name = name  # The name of the user
     self.rooms = []  # List of room names that the user is subscribed to.
     self.current_room = ''  # Name of room that user is currently broadcasting to.
Exemplo n.º 3
0
    def run(self):

        if self.enable_tls:
            context = ssl.SSLContext(ssl.PROTOCOL_TLS)
            #context.load_cert_chain(certfile="/home/daniel/ma-daniel-geiger/floodlight/tls/client.crt",
            #                              keyfile="/home/daniel/ma-daniel-geiger/floodlight/tls/client.key")
            #context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.CERT_OPTIONAL
            context.check_hostname = False
            socket = context.wrap_socket(self.socket,
                                         server_hostname=self.upstream_ip)
        else:
            socket = self.socket

        try:
            socket.connect((self.upstream_ip, self.upstream_port))
            print(self.dpid + " connected!")
        except Exception as e:
            print("failed to connect: " + str(e))
            return

        socket.setblocking(False)

        time.sleep(1)

        self.start_time = self.getCurrentMicroSeconds()

        while True:
            ready_to_read, ready_to_write, error = select.select([socket],
                                                                 [socket], [],
                                                                 TIMEOUT_S)
            if ready_to_read:
                try:
                    data = socket.recv(BUFFER_SIZE)
                except ssl.SSLWantReadError:
                    print("SSLWantReadError")
                    continue
                self.on_message_received(data)
            elif ready_to_write:
                if len(self.messages_to_send) > 0:
                    xid, message_to_send = self.messages_to_send.pop(0)
                    if self.last_packetin_sent - self.start_time > self.warmup_time_s * 1000000 and self.last_packetin_sent < self.should_stop:
                        self.results.append(
                            [self.getCurrentMicroSeconds(), xid])
                    socket.sendall(message_to_send)
                    print("sent " + str(xid))
                    self.last_packetin_sent = self.getCurrentMicroSeconds()
                if self.throughput_mode:
                    threading.Thread(target=self.send_next).start()
            else:
                print("socket error!")

            if self.getCurrentMicroSeconds() - self.should_stop > 10000000:
                break

            if not self.throughput_mode and self.getCurrentMicroSeconds(
            ) - self.last_packetin_sent > 2000000:
                print("timeout!")
                self.send_next()

        socket.close()
Exemplo n.º 4
0
async def threaded_connect(socket: socket.socket, hostpair: typing.Tuple[str,
                                                                         int]):
    """Run socket connect in a separate thread"""
    isblocking = socket.gettimeout() is None
    socket.setblocking(True)
    await threadworker(socket.connect, hostpair)
    socket.setblocking(isblocking)
Exemplo n.º 5
0
 def __init__(self, socket, name="new", status="inlobby"):
     socket.setblocking(0)
     self.socket = socket  # socket associate to the player
     self.name = name  # name player
     self.id = str(uuid.uuid4())  # ID player
     self.status = status  # status player ( waitng or game )
     self.is_ready = False  # if player ready to play or no
Exemplo n.º 6
0
 def __init__(self,
              asyncSocketsPool,
              socket,
              recvBufSlot=None,
              sendBufSlot=None):
     if type(self) is XAsyncSocket:
         raise XAsyncSocketException(
             'XAsyncSocket is an abstract class and must be implemented.')
     self._asyncSocketsPool = asyncSocketsPool
     self._socket = socket
     self._recvBufSlot = recvBufSlot
     self._sendBufSlot = sendBufSlot
     self._expireTimeSec = None
     self._state = None
     self._onClosed = None
     try:
         socket.settimeout(0)
         socket.setblocking(0)
         if (recvBufSlot is not None and type(recvBufSlot) is not XBufferSlot) or \
            (sendBufSlot is not None and type(sendBufSlot) is not XBufferSlot) :
             raise Exception()
         asyncSocketsPool.AddAsyncSocket(self)
     except:
         raise XAsyncSocketException(
             'XAsyncSocket : Arguments are incorrects.')
Exemplo n.º 7
0
 def _connection(self, socket):
     '''Signal callback: Invoked on incoming connections.'''
     try:
         socket, addr = socket.accept()
     except EnvironmentError as exc:
         CORE.error('Cannot accept new connection: %s' % (exc, ))
         soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
         resource.setrlimit(resource.RLIMIT_NOFILE, (soft + 2, hard + 2))
         try:
             socket, addr = socket.accept()
             socket.close()
         except EnvironmentError:
             pass
         finally:
             resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))
         return True
     socket.setblocking(0)
     if addr:
         client = '%s:%d' % (addr[0], addr[1])
     else:
         client = ''
     CORE.info('Incoming connection from %s' % client)
     if self.__magic:
         self.__bucket.new(client, socket)
     else:
         self.signal_emit('session_new', client, socket)
     return True
Exemplo n.º 8
0
def CatchAllData(socket,timeout=2):
    #make socket non blocking
    socket.setblocking(0)
    TotalData=[];
    Data='';
    begin=time.time()
    
    while 1:
        #if you got some data, then break after timeout
        if TotalData and time.time()-begin > timeout:
            break
         
        #if you got no data at all, wait a little longer, twice the timeout
        elif time.time()-begin > timeout*2:
            break
        #recv something
        try:
            Data = socket.recv(8192)
            if Data:
                TotalData.append(Data)
                #change the beginning time for measurement
                begin=time.time()
            else:
                #sleep
                time.sleep(0.1)
        except:
            pass
     
    #join all parts to make final string
    return ''.join(TotalData)
Exemplo n.º 9
0
def send(socket, data, color=0x007f00):
    pycom.rgbled(color)
    socket.setblocking(True)
    socket.send(bytes(data))
    socket.setblocking(False)
    time.sleep(0.5)
    pycom.rgbled(0x000000)
Exemplo n.º 10
0
    def __init__(self, game, addresses, port, versionString, adminPassword):
        self.game = game
        self.versionString = versionString
        self.shutdownOrder = False
        self.adminPassword = adminPassword

        self.rawConnections = []
        self.playerCons = []

        self.sockets = []
        self.updating = {}

        self.socketsOpened = []
        self.listening = False

        ### open listener sockets
        for address in addresses:
            try:
                socket = SocketType()
                socket.setblocking(0)
                socket.bind((address, port))
                socket.listen(10)
                socket.setblocking(0)
                print "opened socket on %s:%i" % (address, port)
                self.sockets.append(socket)
                self.socketsOpened.append(address)
                self.listening = True

                tSocket = Thread(name="socket on %s:%i" % (address, port),
                                 target=self.threadListener,
                                 args=(socket, ))
                tSocket.start()
            except Exception, ex:
                print "failed to open socket on %s:" % address, ex[1]
Exemplo n.º 11
0
 def __init__(self, master, key, from_aliases, socket):
     self.master = master
     self.key = key
     self.write_buffer = b'' # used to buffer data to be written
     self.to_aliases = list(self.key[1]) # JIDs to send messages to
     self.to_alias_index = 0 # index used for round-robin scheduling
     self.to_alias_lock = threading.Lock()
     '''
     from_aliases is a
     set of indices that correspond
     to aliases to send messages from.
     The indices are used to access a bot from master's self.bots
     '''
     self.from_aliases = from_aliases # JIDs to send from
     self.id = 0 # the id used to send the next message
     self.last_id_received = 0 # id of the last message that resulted in a write
     self.incomming_message_db = {} # used to lookup chunks of data from id numbers
     self.reading = True # whether to read data from the socket
     self.reading_lock = threading.Lock()
     socket.setblocking(0)
     self.socket = socket
     self.send_rate = 0.0 # rate at which socket has been sending data over the chat server
     self.send_rate_lock = threading.Lock()
     self.time_last_sent = time.time() # time at which the socket last sent a message
     self.avg_send_rate = 0.0    # used for master.take_measurements
Exemplo n.º 12
0
 def _add_connection(self, socket):
     host, port = socket.getpeername()
     self.log.debug("Adding connection from %s:%d", host, port)
     socket.setblocking(0)
     self._pending_connections[socket.fileno()] = (time.time(),
                                                   socket)
     self._poller.register(socket, self.READ_ONLY_MASK)
Exemplo n.º 13
0
def recv(socket):
    #make socket non blocking
    socket.setblocking(0)
     
    #total data partwise in an array
    total_data=[];
    data='';
     
    #beginning time
    begin=time.time()
    while 1:
        #if you got some data, then break after timeout
        if total_data and time.time()-begin > recvTimeout:
            break
         
        #if you got no data at all, wait a little longer
        elif time.time()-begin > recvFirstTimeout:
            break
         
        #recv something
        try:
            data = socket.recv(recvBufferSize)
            if data:
                total_data.append(data)
                #change the beginning time for measurement
                begin=time.time()
            else:
                #sleep for sometime to indicate a gap
                time.sleep(recvIntervalTimer)
        except:
            pass
     
    #join all parts to make final string
    return b''.join(total_data)
Exemplo n.º 14
0
def nonblocking_way():
    sock = socket.socket()
    socket.setblocking(False)
    try:
        sock.connect(('baidu.com', 80))
    except BlockingIOError:
        # 非阻塞过程中可能抛出异常
        pass
    request = 'GET /HTTP/1.0\r\nHost: baidu.com\r\n\r\n'
    data = request.encode('ascii')
    # 不知道socket何时就绪,所以不断尝试发送
    while True:
        try:
            sock.send(data)
            # 直到send不抛出异常,则发送完成
            break
        except OSError:
            pass

    response = b''
    while True:
        try:
            chunk = sock.recv(4096)
            while chunk:
                response += chunk
                chunk = sock.recv(4096)
            break
        except OSError:
            pass
    return response
Exemplo n.º 15
0
def recv_all_data(socket, timeout=2):
    socket.setblocking(0)  # make socket non-blocking

    total_data = []  # make array to store fragments of data received
    data = ''  # capture received data in string to append to total_data array

    begin = time.time()  # start time

    while True:
        if total_data and time.time(
        ) - begin > timeout:  # if you got some data, then break after timeout
            break

        # receive data and decode into string format
        try:
            data = socket.recv(8192)
            dec_data = data.decode()

            # condition to check variable 'data' has any value remaining
            if data:
                total_data.append(
                    dec_data
                )  # if condition passes, append decoded data to total_data array

        except:
            pass

    return ''.join(
        total_data
    )  # join elements in total_data array into a single string and return
Exemplo n.º 16
0
def nextkeygen(socket, id, np):
    socket.setblocking(0)
    global keychange, next_key, moveq, movearray, gameover
    movearray = []
    for i in range(np):
        i = i
        movearray.append("")

    moveq = queue.Queue(maxsize=0)
    gameover = True
    while (gameover == True):
        try:
            data = socket.recv(1024 * 10)
            data = pickle.loads(data)
            if data in ["s", "a", "w", "d"]:
                next_key = data
                keychange = True
                # moveq.put((next_key,id))
                movearray[id] = data

            else:
                next_key = -1
                keychange = False

        except OSError as err:
            continue
Exemplo n.º 17
0
 def _add_connection(self, socket):
     host, port = socket.getpeername()
     self.log.debug("Adding connection from %s:%d", host, port)
     socket.setblocking(0)
     self._pending_connections[socket.fileno()] = (time.time(),
                                                   socket)
     self._poller.register(socket, self.READ_ONLY_MASK)
Exemplo n.º 18
0
    def __init__( self, game, addresses, port, versionString, adminPassword ):
        self.game = game
        self.versionString = versionString
        self.shutdownOrder = False
        self.adminPassword = adminPassword

        self.rawConnections = []
        self.playerCons = []

        self.sockets = []
        self.updating = {}

        self.socketsOpened = [] 
        self.listening = False

        ### open listener sockets
        for address in addresses:
          try:
            socket = SocketType()
            socket.setblocking(0)
            socket.bind( ( address, port ) )
            socket.listen( 10 )
            socket.setblocking( 0 )
            print "opened socket on %s:%i" % (address,port)
            self.sockets.append( socket )
            self.socketsOpened.append( address )
            self.listening = True

            tSocket = Thread( name="socket on %s:%i"%(address,port), target=self.threadListener, args=(socket,) )
            tSocket.start()
          except Exception, ex:
            print "failed to open socket on %s:"%address, ex[1]
def recv_bytes_once(socket):
    socket.setblocking(0)

    ready = select.select([socket], [], [], 3)
    if ready[0]:
        return socket.recv(8192)
    else:
        return []
Exemplo n.º 20
0
    def __init__(self, socket):
        self.socket = socket
        self.text_typed = b""
        self.username = None

        socket.setblocking(False)
        socket.send(
            b'Welcome to the chat server!\r\nPlease enter a username:\r\n')
Exemplo n.º 21
0
def emptySocketBuffer(socket):
    socket.setblocking(False)
    while (True):
        try:
            socket.recv(bufferSize)
        except:
            break
    socket.setblocking(True)
Exemplo n.º 22
0
 def __init__(self, socket, name = "new"):
     socket.setblocking(0)
     self.socket = socket
     self.name = name
     self.is_logged_in = False
     self.has_entered_username = False
     self.password = None
     self.should_quit = False
Exemplo n.º 23
0
 def connect(self, addr):
     self.connected = False
     self.connecting = True
     socket = self.socket
     socket.setblocking(1)
     socket.connect(addr)
     socket.setblocking(0)
     self.addr = addr
     self.handle_connect_event()
Exemplo n.º 24
0
 def run(self):
     for i in range(self.packets):
         try:
             bytes = random._urandom(self.size)
             socket.connect(self.ip, self.port)
             socket.setblocking(0)
             socket.sendto(bytes,(self.ip, self.port))
         except:
             pass
Exemplo n.º 25
0
 def connect(self, addr):
     self.connected = False
     self.connecting = True
     socket = self.socket
     socket.setblocking(1)
     socket.connect(addr)
     socket.setblocking(0)
     self.addr = addr
     self.handle_connect_event()
Exemplo n.º 26
0
 def __init__(self, socket, name="new"):
     socket.setblocking(0)
     self.socket = socket
     self.name = name
     self.cards = []
     self.chips = 1000
     self.chips_in = 0
     self.active = True
     self.turn = False
 def handle_read(self):
     socket, client_address = self.socket.accept()
     log.info("New connection from %s:%d" % (client_address[0], client_address[1]))
     socket.setblocking(0)
     connection = self.ConnectionHandlerClass(socket, client_address, self)
     self.connections.add(connection)
     log.debug("Total connections: " + str(len(self.connections)))
     self.register_error(connection)
     connection.new_connection()
Exemplo n.º 28
0
 def accept_new(self):
     """
     Acepta una nueva conexión
     """
     socket, address = self.master_socket.accept()
     socket.setblocking(0)
     connec = Connection(socket, address)
     connec.task = RequestHandlerTask(self)
     self.append(connec)
Exemplo n.º 29
0
 def _add_connection(self, socket):
     host, port = socket.getpeername()
     self.log.debug("Adding connection %s:%d", host, port)
     socket.setblocking(0)
     self._pending_connections[socket.fileno()] = (time.time(), socket)
     if _is_handshaking(socket):
         self._poller.register(socket, select.POLLIN | select.POLLOUT)
     else:
         self._poller.register(socket, select.POLLIN)
Exemplo n.º 30
0
 def run(self):
     for i in range(self.packets):
         try:
             bytes = random._urandom(self.size)
             socket.connect(self.ip, self.port)
             socket.setblocking(0)
             socket.sendto(bytes, (self.ip, self.port))
         except:
             pass
Exemplo n.º 31
0
	def handle_accept(self, fd):
		socket, addr = fd.accept()
		logger.info("Client Connecting...")
		self.add_session(socket)
		socket.setblocking(False)
		self.inputs.append(socket)
		self.outputs.append(socket)
		self.exceptions.append(socket)
		pass
Exemplo n.º 32
0
 def _add_connection(self, socket):
     host, port = socket.getpeername()
     self.log.debug("Adding connection %s:%d", host, port)
     socket.setblocking(0)
     self._pending_connections[socket.fileno()] = (time.time(),
                                                   socket)
     if _is_handshaking(socket):
         self._poller.register(socket, select.POLLIN | select.POLLOUT)
     else:
         self._poller.register(socket, select.POLLIN)
Exemplo n.º 33
0
 def readfromsocket(self, socket, timeoutinseconds):
     socket.setblocking(0)
     data = ""
     ready = select.select([socket], [], [], timeoutinseconds)
     if ready[0]:
         try:
             data = socket.recv(4096)
         except Exception as e:
             pass  #this is possible when connection is broken by client at this point
     return data
Exemplo n.º 34
0
 def __client_add(self, socket, raddr):
     if len(self.connected_clients) > self.NJSP_MAX_CLIENTS:
         self._print("To many connections, new connection rejected")
         socket.close()
     else:
         socket.setblocking(0)
         queue = collections.deque(self.ringbuffer, self.NJSP_PACKET_BUFFER_SIZE * 2)
         queue.appendleft(self.init_data)
         self.connected_clients.update({socket: queue})
         self._print("New client %s connected" % (str(raddr)))
Exemplo n.º 35
0
		def handle_accept(self):
			socket, address = self.accept()
			if socket is None:
				pass
			elif self.accept_handler_class is None:
				pass
			else:
				handler = self.accept_handler_class()
				socket.setblocking(0)
				handler(socket, address)
Exemplo n.º 36
0
 def readfromsocket(self,socket, timeoutinseconds):
     socket.setblocking(0)
     data = ""
     ready = select.select([socket], [], [], timeoutinseconds)
     if ready[0]:
         try:
             data = socket.recv(4096)
         except Exception as e:
             pass #this is possible when connection is broken by client at this point
     return data
Exemplo n.º 37
0
	def handleSocket(self, socket, address):
		socket.setblocking(0)
		
		clients, handler = min([(len(handler.clients), handler) for handler in self.handlers])
		
		if clients < self.MAX_CLIENTS:
			print("PEER [%s:%d] assigned to thread '%s'" % (address[0], address[1], handler.thread.getName()))
			handler.connect(socket)
		else:
			self.closeSocket(socket)
Exemplo n.º 38
0
def recvFullResponse(socket, timeout=3.0):
    # using non blocking sockets
    socket.setblocking(0)

    # variables to hold our partial and final completed data
    # received from the server
    allData = list()
    partialData = ''

    # begin counting time for timeout
    startTime = time.time()

    # variable to determine how much data we want to receive
    bytesSize = 1024

    while True:
        # we don't need to wait if we didn't receive any further data
        # than what we already received
        if allData and time.time() - startTime > timeout:
            break
        # wait double timeout if we didn't get any data at all
        # then break with a readable message to the user
        elif time.time() - startTime > timeout * 2:
            return "Time out and No Data Recieved"
        else:
            # try catch block
            # trying to receive data if nothing received we just do
            # another loop till the server responded with some data
            try:
                # receiving data
                partialData = socket.recv(bytesSize)
                # check if the get request result status is 200 OK
                # the bytesSize variable is used to not recheck
                # for each and every next part of the data
                if bytesSize == 1024 and (str(partialData)).find("200 OK") < 0:
                    return ''.join(partialData)
                else:
                    bytesSize = 4096
                    if partialData:
                        # append new data to already received data
                        allData.append(partialData)
                        # for sure reset start time if we get data
                        # to be sure we didn't get timeout before
                        # data receiving completion
                        startTime = time.time()
                    # wait for a while before doing another loop
                    else:
                        time.sleep(0.1)

            except:
                pass

    # use join with empty byte to return data
    # in a one byte sequence, for later extracting header purposes
    return b''.join(allData)
Exemplo n.º 39
0
  def client_connect(self, socket, address):
  #add socket. funcs 
    socket.setblocking(0)
    client = Client(socket, address)
    print "New connection from ", address

    self.active_client_list.append(client)
    #time = now() - no time
    self.client_history.append(client) #add time as second in tuple

    return (client)
Exemplo n.º 40
0
 def create_connection(controller_info, switch):
   ''' Connect switches to controllers. May raise a TimeoutError '''
   # TODO(cs): move this into a ConnectionFactory class
   socket = connect_socket_with_backoff(controller_info.address,
                                        controller_info.port,
                                        max_backoff_seconds=8)
   # Set non-blocking
   socket.setblocking(0)
   io_worker = DeferredIOWorker(self.io_master.create_worker_for_socket(socket))
   connection = DeferredOFConnection(io_worker, controller_info.cid, switch.dpid, self.god_scheduler)
   return connection
Exemplo n.º 41
0
	def check_alive(self,socket):
		socket.setblocking(False)
		for i in range(100):
			try:
				x = socket.recv(1)
			except:
				return False
			if len(x) == 0:
				return False
			sleep(0.01)
		socket.setblocking(True)
		return True
Exemplo n.º 42
0
 def register(self, socket, address, read=True, write=True, timeout=60):
     socket.settimeout(timeout)
     socket.setblocking(False)
     events = (selectors.EVENT_READ if read else 0) | (selectors.EVENT_WRITE
                                                       if write else 0)
     connection = Connection(address)
     data = types.SimpleNamespace(
         connection=connection,
         address=address,
     )
     self.selector.register(socket, events, data=data)
     return connection
Exemplo n.º 43
0
    def loop(self):
        
        mask = select.POLLHUP | select.POLLERR

        self.epoll.register(self.server.fileno(), select.POLLIN | mask)

        while True:
            events = self.epoll.poll(self.EVENT_TIMEOUT_SECONDS)
            for fileno, event in events:
                if fileno == self.server.fileno():
                    try:
                        socket, client_address = self.server.accept()
                        socket.setblocking(0)
                        connection = Connection(socket)
                        self.connections[socket.fileno()] = connection
                        self.epoll.register(socket.fileno(), select.POLLIN | mask)
                        connection.last_event_time = time.time()
                    except:
                        pass
                else:
                    connection = self.connections[fileno]
                    connection.last_event_time = time.time()
                    if event & select.EPOLLERR or event & select.EPOLLHUP:
                        self.drop_connection(connection)
                    if event & select.POLLIN:
                        try:
                            data = connection.socket.recv(4096)
                        except:
                            print 'sock err'
                            self.drop_connection(connection)
                            continue
                        if data and data != '':
                            connection.on_recv(data)

                            if connection.state == connection.STATE_RESPONDING:
                                self.epoll.modify(fileno, select.EPOLLOUT | mask)
                            elif connection.state == connection.STATE_DONE:
                                self.drop_connection(connection)
                                continue
                        else:
                            self.drop_connection(connection)
                            continue

                    elif event & select.EPOLLOUT:
                        connection.respond()
                        if connection.state == connection.STATE_DONE:
                            self.drop_connection(connection)
                            continue

            now = time.time()
            for conn in self.connections.values():
                if now - conn.last_event_time > self.EVENT_TIMEOUT_SECONDS:
                    self.drop_connection(conn)
Exemplo n.º 44
0
 def create_connection(controller_info, switch):
   ''' Connect switches to controllers. May raise a TimeoutError '''
   while controller_info.address == "__address__":
     log.debug("Waiting for controller address for %s..." % controller_info.label)
     time.sleep(5)
   # TODO(cs): move this into a ConnectionFactory class
   socket = connect_socket_with_backoff(controller_info.address,
                                        controller_info.port,
                                        max_backoff_seconds=1024)
   # Set non-blocking
   socket.setblocking(0)
   io_worker = DeferredIOWorker(self.io_master.create_worker_for_socket(socket))
   connection = DeferredOFConnection(io_worker, controller_info.cid, switch.dpid, self.openflow_buffer)
   return connection
Exemplo n.º 45
0
	def _connection( self, socket ):
		'''Signal callback: Invoked on incoming connections.'''
		socket, addr = socket.accept()
		socket.setblocking( 0 )
		if addr:
			client = '%s:%d' % ( addr[ 0 ], addr[ 1 ] )
		else:
			client = ''
		CORE.info( 'Incoming connection from %s' % client )
		if self.__magic:
			self.__bucket.new( client, socket )
		else:
			self.signal_emit( 'session_new', client, socket )
		return True
Exemplo n.º 46
0
 def receive(socket, size):
     """ Read all content of the socket """
     buf = ""
     _hasData = True 
     while _hasData:
         socket.setblocking( 0)
         try:
             _data = socket.recv(size)
             if( _data):
                 buf += _data
             else:
                 _hasData = False
         except:
             _hasData = False
     return buf
Exemplo n.º 47
0
    def __init__ (self, socket, pid, server):
        """
        Create a new BlockingChannelClient instance.

        @param socket (socket) The channel socket.
        @param pid    (int)    The process id.
        @param server (Server) The Server instance within which this BlockingChannelClient is being created.
        """

        ChannelClient.__init__(self, socket, pid, server)

        self._is_blocking = True

        # re-enable blocking
        socket.setblocking(1)
Exemplo n.º 48
0
	def receive(self, socket):
		buf = "" # Variable dans laquelle on stocke les données
		_hasData = True # Nous permet de savoir si il y de données à lire
		while _hasData:
			# On passe le socket en non-bloquant
			socket.setblocking(0)
			try:
				_data = socket.recv(256)
				if(_data):
					buf += _data
				else:
					# Déconnexion du client
					_hasData = False
			except:
				_hasData = False
		return buf
Exemplo n.º 49
0
    def _incoming_connection(self, socket):
        socket, addr = socket.accept()
        socket.setblocking(0)
        if addr:
            client = "%s:%d" % (addr[0], addr[1])
        else:
            client = ""

        debug(LOGERROR, "incoming connection: %s" % client)

        # create new state
        state = {"clientaddr": client, "nextId": 1, "inbuffer": "", "outbuffer": "", "targetdir": "", "filelist": {}}
        self._connectionstates[socket] = state
        notifier.socket_add(socket, self._receive_data)

        return True
Exemplo n.º 50
0
    def add_client(self, socket):

        type = socket.recv(1)
        user = socket.recv(32).strip()
        logging.warn("Type: %s, User: %s", type, user)
        if type == "0":
            # self.sendList[user] = socket
            s_list[user] = socket
            logging.warn("Added client. Current number: %d", len(s_list.keys()))
        if type == "1":
            # self.recvList[user] = socket
            r_list[user] = socket
        # with self.sendListLock:
        # self.sendList.append(socket)

        socket.setblocking(1)
Exemplo n.º 51
0
 def __init__(self, master, key, from_aliases, socket):
     self.master=master
     self.key=key
     self.running=True
     self.running_lock=threading.Lock()
     self.reading=True
     self.reading_lock=threading.Lock()
     self.writing=True
     self.writing_lock=threading.Lock()
     self.incomming_message_queue=queue.Queue()
     self.to_aliases=list(self.key[1])
     self.to_alias_index=0
     self.to_alias_lock=threading.Lock()
     self.from_aliases=from_aliases
     self.id=0
     socket.setblocking(1)
     self.socket=socket
Exemplo n.º 52
0
 def __init__(self, socket, password, establisher):
    threading.Thread.__init__(self)
    socket.setblocking(True)
    global allConnections
    allConnections.append(self)
    self.establisher = establisher
    self.socket = socket
    self.password = password
    #get the AES object (password must be 16, 24 or 32 bytes long)
    if password != "":
       if not cryptAvailable:
          return	#TODO
       if len(password) <= 8:
          fill = 8
       fill += 8 - (len(password) % 8)
       passw = password + "\0" * fill
       self.crypt = AES.new(passw, AES.MODE_ECB)
    def receiveMsg(self,socket, waittime):

        socket.setblocking(0)

        finaldata = []

        data = ''

        start_time = time.time()

        while 1:

            if data and time.time()-start_time > waittime:

                break

            elif time.time()-start_time > waittime*2:

                break

        try:

            data = socket.recv(8192)

            if data:

                finaldata.append(data)

                begin = time.time()

            else:

                time.sleep(0.1)

        except:

            pass

        print(finaldata)

        return ''.join(finaldata)
        
Exemplo n.º 54
0
 def __init__(self, master, key, socket):
     self.master=master
     self.key=key
     self.aliases=list(key[1])
     self.id=0
     self.last_id_received=0
     self.incomming_messages=[]
     self.alias_index=0
     self.buffer=b''
     self.running=True
     self.running_lock=threading.Lock()
     self.reading=True
     self.reading_lock=threading.Lock()
     self.writing=True
     self.writing_lock=threading.Lock()
     self.alias_lock=threading.Lock()
     self.id_lock=threading.Lock()
     self.bot_lock=threading.Lock()
     self.bot_index=0
     socket.setblocking(1)
     self.socket=socket
Exemplo n.º 55
0
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


port = 5554
ip = "192.168.0.1"

# assemble a byte array of arbitrary binary values for testing
MESSAGE = bytearray("")
for i in range(0, 255):
    # for i in range ( 0 , 510):
    MESSAGE.append(int(i % 128))
CURRENT = MESSAGE

socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.setblocking(False)

# send initial single-byte handshake, requesting  slot 1
socket.sendto(b"\1", (ip, port))

i = 0
seconds_ticker = time.clock()
while 1:
    i = i + 1
    # first two bytes are SRC and TGT, then 100 bytes of DATA
    socket.sendto(b"\1" + b"\2" + MESSAGE, (ip, port))

    # every few seconds upp the packet size by 10 from 100-240
    if time.clock() > seconds_ticker + 1:
        seconds_ticker = time.clock()
        if len(CURRENT) < 510:
Exemplo n.º 56
0
def process_data(entity, data):
	func_list = data.split(' ')
	for func_name in func_list:
		if len(func_name) > 0 :
			func = getattr(entity, func_name)
			if not func:
				print 'function %s not found!' % func_name
				continue
			func()

if __name__ == '__main__':
	socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	socket.bind(('127.0.0.1', 4000))
	socket.listen(0)
	socket.setblocking(0)
	entity = entity.entity()
	clients = {}
	while True:
		conn = None
		addr = None
		try:
			conn, addr = socket.accept()
		except:pass
		if conn:
			print 'find new connection'
			clients[addr[0]+str(addr[1])] = conn

		for client_id, client in clients.iteritems():
			data = ''
			while True:
Exemplo n.º 57
0
 def _remove_connection(self, socket):
     self._poller.unregister(socket)
     del self._pending_connections[socket.fileno()]
     socket.setblocking(1)
     host, port = socket.getpeername()
     self.log.debug("Connection removed from %s:%d", host, port)
Exemplo n.º 58
0
 def __init__(self, socket, name = "new"):
     socket.setblocking(0)
     self.socket = socket
     self.name = name