Ejemplo n.º 1
0
 def _bind(self, hostname, port, max_tries=1):
     """ Bind the bsd socket. Launches a dedicated thread that waits
     for incoming connections and to do the handshaking procedure.
     """
     
     # Create socket.
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     
     # Set buffer size to be fairly small (less than 10 packages)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SOCKET_BUFFERS_SIZE)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFFERS_SIZE)
     
     # Apply SO_REUSEADDR when binding, so that an improperly closed
     # socket on the same port will not prevent us from connecting.
     # It also allows a connection to bind at the same port number,
     # but only after the previous binding connection has connected
     # (and has closed the listen-socket).
     #
     # SO_REUSEADDR means something different on win32 than it does
     # for Linux sockets. To get the intended behavior on Windows,
     # we don't have to do anything. Also see:
     #  * http://msdn.microsoft.com/en-us/library/ms740621%28VS.85%29.aspx
     #  * http://twistedmatrix.com/trac/ticket/1151
     #  * http://www.tcpipguide.com/free/t_TCPPortsConnectionsandConnectionIdentification-2.htm
     if not sys.platform.startswith('win'):
         s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     
     # Try all ports in the specified range
     for port2 in range(port, port+max_tries):
         try:
             s.bind((hostname,port2))
             break
         except Exception:
             # Raise the socket exception if we were asked to try
             # just one port. Otherwise just try the next
             if max_tries == 1:
                 raise
             continue
     else:
         # We tried all ports without success
         tmp = str(max_tries)
         tmp = "Could not bind to any of the " + tmp + " ports tried."
         raise IOError(tmp)
     
     # Tell the socket it is a host. Backlog of at least 1 to avoid linux
     # kernel from detecting SYN flood and throttling the connection (#381)
     s.listen(1)
     
     # Set connected (status 1: waiting for connection)
     # Will be called with status 2 by the hostThread on success
     self._set_status(STATUS_WAITING, s)
     
     # Start thread to wait for a connection
     # (keep reference so the thread-object stays alive)
     self._hostThread = HostThread(self, s)
     self._hostThread.start()
Ejemplo n.º 2
0
    def _bind(self, hostname, port, max_tries=1):
        """ Bind the bsd socket. Launches a dedicated thread that waits
        for incoming connections and to do the handshaking procedure.
        """

        # Create socket.
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Set buffer size to be fairly small (less than 10 packages)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SOCKET_BUFFERS_SIZE)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFFERS_SIZE)

        # Apply SO_REUSEADDR when binding, so that an improperly closed
        # socket on the same port will not prevent us from connecting.
        # It also allows a connection to bind at the same port number,
        # but only after the previous binding connection has connected
        # (and has closed the listen-socket).
        #
        # SO_REUSEADDR means something different on win32 than it does
        # for Linux sockets. To get the intended behavior on Windows,
        # we don't have to do anything. Also see:
        #  * http://msdn.microsoft.com/en-us/library/ms740621%28VS.85%29.aspx
        #  * http://twistedmatrix.com/trac/ticket/1151
        #  * http://www.tcpipguide.com/free/t_TCPPortsConnectionsandConnectionIdentification-2.htm
        if not sys.platform.startswith("win"):
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Try all ports in the specified range
        for port2 in range(port, port + max_tries):
            try:
                s.bind((hostname, port2))
                break
            except Exception:
                # Raise the socket exception if we were asked to try
                # just one port. Otherwise just try the next
                if max_tries == 1:
                    raise
                continue
        else:
            # We tried all ports without success
            tmp = str(max_tries)
            tmp = "Could not bind to any of the " + tmp + " ports tried."
            raise IOError(tmp)

        # Tell the socket it is a host. Backlog of at least 1 to avoid linux
        # kernel from detecting SYN flood and throttling the connection (#381)
        s.listen(1)

        # Set connected (status 1: waiting for connection)
        # Will be called with status 2 by the hostThread on success
        self._set_status(STATUS_WAITING, s)

        # Start thread to wait for a connection
        # (keep reference so the thread-object stays alive)
        self._hostThread = HostThread(self, s)
        self._hostThread.start()
Ejemplo n.º 3
0
    def _connect(self, hostname, port, timeout=1.0):
        """ Connect to a bound socket.
        """

        # Create socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Set buffer size to be fairly small (less than 10 packages)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SOCKET_BUFFERS_SIZE)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFFERS_SIZE)

        # Refuse rediculously low timeouts
        if timeout <= 0.01:
            timeout = 0.01

        # Try to connect
        ok = False
        timestamp = time.time() + timeout
        while not ok and time.time() < timestamp:
            try:
                s.connect((hostname, port))
                ok = True
            except socket.error:
                pass
            except socket.timeout:
                pass
            time.sleep(timeout / 100.0)

        # Did it work?
        if not ok:
            type, value, tb = sys.exc_info()
            del tb
            err = str(value)
            raise IOError("Cannot connect to %s on %i: %s" %
                          (hostname, port, err))

        # Shake hands
        h = HandShaker(s)
        success, info = h.shake_hands_as_client(self.id1)

        # Problem?
        if not success:
            self._set_status(0)
            if not info:
                info = 'problem during handshake'
            raise IOError('Could not connect: ' + info)

        # Store id
        self._id2, self._pid2 = info

        # Set connected (status 3: connected as client)
        self._set_status(STATUS_CONNECTED, s)
Ejemplo n.º 4
0
 def _connect(self, hostname, port, timeout=1.0):
     """ Connect to a bound socket.
     """
     
     # Create socket
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     
     # Set buffer size to be fairly small (less than 10 packages)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SOCKET_BUFFERS_SIZE)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFFERS_SIZE)
     
     # Refuse rediculously low timeouts
     if timeout<= 0.01:
         timeout = 0.01
     
     # Try to connect
     ok = False
     timestamp = time.time() + timeout
     while not ok and time.time()<timestamp:
         try:
             s.connect((hostname, port))
             ok = True
         except socket.error:
             pass
         except socket.timeout:
             pass
         time.sleep(timeout/100.0)
     
     # Did it work?
     if not ok:
         type, value, tb = sys.exc_info()
         del tb
         err = str(value)
         raise IOError("Cannot connect to %s on %i: %s" % (hostname, port, err))
     
     # Shake hands
     h = HandShaker(s)
     success, info = h.shake_hands_as_client(self.id1)
     
     # Problem?
     if not success:
         self._set_status(0)
         if not info:
             info = 'problem during handshake'
         raise IOError('Could not connect: '+ info)
     
     # Store id
     self._id2, self._pid2 = info
     
     # Set connected (status 3: connected as client)
     self._set_status(STATUS_CONNECTED, s)
Ejemplo n.º 5
0
    def _register_receiving_channel(self, channel, slot, slotname=''):
        """ _register_receiving_channel(channel, slot, slotname='')
        
        The channel objects use this method to register themselves 
        at a particular slot.
        
        """

        # Check if this slot is free
        if slot in self._receiving_channels:
            raise ValueError("Slot not free: " + str(slotname))

        # Register
        self._receiving_channels[slot] = channel
Ejemplo n.º 6
0
 def _register_receiving_channel(self, channel, slot, slotname=''):
     """ _register_receiving_channel(channel, slot, slotname='')
     
     The channel objects use this method to register themselves 
     at a particular slot.
     
     """ 
     
     # Check if this slot is free
     if slot in self._receiving_channels:
         raise ValueError("Slot not free: " + str(slotname))
     
     # Register
     self._receiving_channels[slot] = channel
Ejemplo n.º 7
0
 def run(self):
     """ run()
     The server's main loop.
     """
     
     # Get socket instance
     s = self._bsd_socket
     
     # Notify
     hostname, port = s.getsockname()
     if self._verbose:
         print('Yoton: hosting at %s, port %i' % (hostname, port))
     
     # Tell the socket it is a host, accept multiple
     s.listen(1)
     
     # Set timeout so that we can check _stop_me from time to time
     self._bsd_socket.settimeout(0.25)
     
     # Enter main loop
     while not self._stop_me:
         try:
             s, addr = self._bsd_socket.accept()
         except socket.timeout:
             pass
         except InterruptedError:
             pass
         else:
             # Show handling?
             if self._verbose:
                 print('handling request from: '+str(addr))
             # Handle request
             if self._async :
                 rh = SocketHandler(self, s)
                 rh.start()
             else:
                 self._handle_connection(s)
     
     # Close down
     try:
         self._bsd_socket.close()
     except socket.error:
         pass
Ejemplo n.º 8
0
    def run(self):
        """ run()
        The server's main loop.
        """

        # Get socket instance
        s = self._bsd_socket

        # Notify
        hostname, port = s.getsockname()
        if self._verbose:
            print("Yoton: hosting at %s, port %i" % (hostname, port))

        # Tell the socket it is a host, accept multiple
        s.listen(1)

        # Set timeout so that we can check _stop_me from time to time
        self._bsd_socket.settimeout(0.25)

        # Enter main loop
        while not self._stop_me:
            try:
                s, addr = self._bsd_socket.accept()
            except socket.timeout:
                pass
            except InterruptedError:
                pass
            else:
                # Show handling?
                if self._verbose:
                    print("handling request from: " + str(addr))
                # Handle request
                if self._async:
                    rh = SocketHandler(self, s)
                    rh.start()
                else:
                    self._handle_connection(s)

        # Close down
        try:
            self._bsd_socket.close()
        except socket.error:
            pass
Ejemplo n.º 9
0
 def writeErr(err):
     sys.__stderr__.write(str(err) + "\n")
     sys.__stderr__.flush()
Ejemplo n.º 10
0
    # Send request
    send_all(s, request, True)
    
    # Receive reply
    reply = recv_all(s, timeout)
    
    # Close socket
    try:
        s.close()
    except socket.error:
        pass
    
    # Done
    return reply


if __name__ == '__main__':
    
    class Lala(RequestServer):
        def handle_request(self, req):
            print('REQ:',repr(req))
            return "The current time is %i" % time.time()
        
    s = Lala('localhost:test', 0, 1)
    s.start()
    if False:
        print(do_request('localhost:test', 'wait', 5))
        for i in range(10):
            print(do_request('localhost:test', 'hi'+str(i)))
    # do_request('localhost:test', 'wait'); do_request('localhost:test', 'hi');
Ejemplo n.º 11
0
    # Send request
    send_all(s, request, True)

    # Receive reply
    reply = recv_all(s, timeout)

    # Close socket
    try:
        s.close()
    except socket.error:
        pass

    # Done
    return reply


if __name__ == "__main__":

    class Lala(RequestServer):
        def handle_request(self, req):
            print("REQ:", repr(req))
            return "The current time is %i" % time.time()

    s = Lala("localhost:test", 0, 1)
    s.start()
    if False:
        print(do_request("localhost:test", "wait", 5))
        for i in range(10):
            print(do_request("localhost:test", "hi" + str(i)))
    # do_request('localhost:test', 'wait'); do_request('localhost:test', 'hi');
Ejemplo n.º 12
0
 def writeErr(err):
     sys.__stderr__.write(str(err)+'\n')
     sys.__stderr__.flush()
Ejemplo n.º 13
0
    # Send request
    send_all(s, request, True)
    
    # Receive reply
    reply = recv_all(s, timeout)
    
    # Close socket
    try:
        s.close()
    except socket.error:
        pass
    
    # Done
    return reply


if __name__ == '__main__':
    
    class Lala(RequestServer):
        def handle_request(self, req):
            print('REQ:',repr(req))
            return "The current time is %i" % time.time()
        
    s = Lala('localhost:test', 0, 1)
    s.start()
    if False:
        print(do_request('localhost:test', 'wait', 5))
        for i in range(10):
            print(do_request('localhost:test', 'hi'+str(i)))
    # do_request('localhost:test', 'wait'); do_request('localhost:test', 'hi');
Ejemplo n.º 14
0
 def writeErr(err):
     sys.__stderr__.write(str(err) + '\n')
     sys.__stderr__.flush()