Пример #1
0
    def ping(server_port, timeout=1, error_only=False):
        """ Returns whether the server is running on 'server_port'.

            If error_only, return False only if there was an error (ie the
            socket is closed).
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.bind(('localhost', 0))
        sock.listen(1)
        try:
            port = str(sock.getsockname()[1])
            send_port(server_port, "ping", port, timeout=timeout)
            try:
                server, address = accept_no_intr(sock)
                try:
                    command, arguments = receive(server)
                    return command == "__status__" and bool(int(arguments))
                finally:
                    try:
                        server.shutdown(socket.SHUT_RD)
                    except:
                        pass
            except socket.error:
                # 'sock' may have timed out, so use try..except.
                try:
                    sock.shutdown(socket.SHUT_RD)
                except:
                    pass
                return False
        except:
            try:
                sock.shutdown(socket.SHUT_RD)
            except:
                pass
Пример #2
0
    def ping(server_port, timeout=1, error_only=False):
        """ Returns whether the server is running on 'server_port'.

            If error_only, return False only if there was an error (ie the
            socket is closed).
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.bind(('localhost', 0))
        sock.listen(1)
        try:
            port = str(sock.getsockname()[1])
            send_port(server_port, "ping", port, timeout=timeout)
            try:
                server, address = accept_no_intr(sock)
                try:
                    command, arguments = receive(server)
                    return command == "__status__" and bool(int(arguments))
                finally:
                    try:
                        server.shutdown(socket.SHUT_RD)
                    except:
                        pass
            except socket.error:
                # 'sock' may have timed out, so use try..except.
                try:
                    sock.shutdown(socket.SHUT_RD)
                except:
                    pass
                return False
        except:
            try:
                sock.shutdown(socket.SHUT_RD)
            except:
                pass
Пример #3
0
    def main(self, port=0):
        """ Starts the server mainloop. If 'port' is specified, the assumption
            is that this Server was spawned from an object on said port. The
            Server will inform the Client that it has been created, and if fails
            to contact the client, this function will return.
        """
        try:
            # Start listening *before* we (potentially) inform the spawner that
            # we are working. This means that if the spawner tries to register,
            # we will be ready.
            logger.info("Server listening on port %i..." % self._port)
            self._sock.listen(5)
            self._sock.settimeout(300)

            # If necessary, inform the launcher that we have initialized
            # correctly by telling it our port
            if port:
                if not send_port(port, "__port__", str(self._port), timeout=5):
                    msg = "Server could not contact spawner. Shutting down..."
                    logger.warning(msg)
                    return

            # Start the mainloop
            while True:
                try:
                    client, address = accept_no_intr(self._sock)
                except socket.timeout:
                    # Every 5 minutes of inactivity, we trigger a garbage
                    # collection. We do this to make sure the server doesn't
                    # stay on, with dead process as zombies.
                    self._gc()
                    continue
                try:
                    if address[0] != '127.0.0.1':
                        msg = "Server received connection from a non-local " \
                            "party (port %s). Ignoring..."
                        logger.warning(msg, address[0])
                        continue
                    command, arguments = receive(client)
                    logger.debug("Server received: %s %s", command, arguments)
                    if command == "send":
                        port, command, arguments = arguments.split(MESSAGE_SEP)
                        self._send_from(int(port), command, arguments)
                    elif command == "register":
                        port, type, other_type = arguments.split(MESSAGE_SEP)
                        self._register(int(port), type, other_type)
                    elif command == "unregister":
                        self._unregister(int(arguments))
                    elif command == "ping":
                        self._send_to(int(arguments), "__status__", "1")
                    elif command == "spawn":
                        self._spawn(arguments)
                    else:
                        logger.error("Server received unknown command: %s %s",
                                     command, arguments)
                finally:
                    client.close()
        finally:
            self._sock.close()
Пример #4
0
    def main(self, port=0):
        """ Starts the server mainloop. If 'port' is specified, the assumption
            is that this Server was spawned from an object on said port. The
            Server will inform the Client that it has been created, and if fails
            to contact the client, this function will return.
        """
        try:
            # Start listening *before* we (potentially) inform the spawner that
            # we are working. This means that if the spawner tries to register,
            # we will be ready.
            logger.info("Server listening on port %i..." % self._port)
            self._sock.listen(5)
            self._sock.settimeout(300)

            # If necessary, inform the launcher that we have initialized
            # correctly by telling it our port
            if port:
                if not send_port(port, "__port__", str(self._port), timeout=5):
                    msg = "Server could not contact spawner. Shutting down..."
                    logger.warning(msg)
                    return

            # Start the mainloop
            while True:
                try:
                    client, address = accept_no_intr(self._sock)
                except socket.timeout:
                    # Every 5 minutes of inactivity, we trigger a garbage
                    # collection. We do this to make sure the server doesn't
                    # stay on, with dead process as zombies.
                    self._gc()
                    continue
                try:
                    if address[0] != '127.0.0.1':
                        msg = "Server received connection from a non-local " \
                            "party (port %s). Ignoring..."
                        logger.warning(msg, address[0])
                        continue
                    command, arguments = receive(client)
                    logger.debug("Server received: %s %s", command, arguments)
                    if command == "send":
                        port, command, arguments = arguments.split(MESSAGE_SEP)
                        self._send_from(int(port), command, arguments)
                    elif command == "register":
                        port, type, other_type = arguments.split(MESSAGE_SEP)
                        self._register(int(port), type, other_type)
                    elif command == "unregister":
                        self._unregister(int(arguments))
                    elif command == "ping":
                        self._send_to(int(arguments), "__status__", "1")
                    elif command == "spawn":
                        self._spawn(arguments)
                    else:
                        logger.error("Server received unknown command: %s %s",
                                     command, arguments)
                finally:
                    client.close()
        finally:
            self._sock.close()
Пример #5
0
    def run(self):
        # Get the server port, spawning it if necessary
        server_port = get_server_port()
        if server_port == -1 or not Server.ping(server_port, timeout=5):
            if len(self.client.server_prefs):
                # Spawn the server
                logger.info("Client spawning Server...")
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(5)
                sock.bind(('localhost', 0))
                sock.listen(1)
                port = sock.getsockname()[1]
                args = self.client.server_prefs + ( port, )
                code = "from envisage.plugins.remote_editor.communication." \
                    "server import main; main(r'%s', '%s', %i)" % args
                spawn_independent([sys.executable, '-c', code])

                # Await a reponse from the server
                try:
                    server, address = accept_no_intr(sock)
                    try:
                        command, arguments = receive(server)
                        if command == "__port__":
                            self.client._server_port = int(arguments)
                        else:
                            raise socket.error
                    finally:
                        # Use try...except to handle timeouts
                        try:
                            server.shutdown(socket.SHUT_RD)
                        except:
                            pass
                except socket.error, e:
                    logger.error(repr(e))
                    logger.error("Client spawned a non-responsive Server! " \
                                     "Unregistering...")
                    self.client.error = True
                    self.client.unregister()
                    return
                finally:
                    sock.close()
Пример #6
0
    def run(self):
        # Get the server port, spawning it if necessary
        server_port = get_server_port()
        if server_port == -1 or not Server.ping(server_port, timeout=5):
            if len(self.client.server_prefs):
                # Spawn the server
                logger.info("Client spawning Server...")
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(5)
                sock.bind(('localhost', 0))
                sock.listen(1)
                port = sock.getsockname()[1]
                args = self.client.server_prefs + (port, )
                code = "from envisage.plugins.remote_editor.communication." \
                    "server import main; main(r'%s', '%s', %i)" % args
                spawn_independent([sys.executable, '-c', code])

                # Await a reponse from the server
                try:
                    server, address = accept_no_intr(sock)
                    try:
                        command, arguments = receive(server)
                        if command == "__port__":
                            self.client._server_port = int(arguments)
                        else:
                            raise socket.error
                    finally:
                        # Use try...except to handle timeouts
                        try:
                            server.shutdown(socket.SHUT_RD)
                        except:
                            pass
                except socket.error, e:
                    logger.error(repr(e))
                    logger.error("Client spawned a non-responsive Server! " \
                                     "Unregistering...")
                    self.client.error = True
                    self.client.unregister()
                    return
                finally:
                    sock.close()
Пример #7
0
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import RPi.GPIO as gpio
import util
import datetime

gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
pin = 18

while True:
    bits = list(util.receive(pin))
    if bits:
        res = []
        for i in range(len(bits) // 8):
            byte = bits[i*8:(i+1)*8]
            b = 0
            for i in range(8):
                b += (1 << i) * byte[i]
            res.append(chr(b))
        data = ''.join(res)
        print('%s:\n\t%r \n\t(%d bits)' % (datetime.datetime.now().ctime(), data, len(bits),))

Пример #8
0
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import RPi.GPIO as gpio
import util
import datetime

gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
pin = 18

while True:
    bits = list(util.receive(pin))
    if bits:
        res = []
        for i in range(len(bits) // 8):
            byte = bits[i * 8:(i + 1) * 8]
            b = 0
            for i in range(8):
                b += (1 << i) * byte[i]
            res.append(chr(b))
        data = ''.join(res)
        print('%s:\n\t%r \n\t(%d bits)' % (
            datetime.datetime.now().ctime(),
            data,
            len(bits),
        ))
Пример #9
0
        # Start the loop to listen for commands from the Server
        logger.info("Client listening on port %i..." % self.client._port)
        try:
            while not self._finished:
                server, address = accept_no_intr(sock)

                # Reject non-local connections
                if address[0] != '127.0.0.1':
                    msg = "Client on port %s received connection from a " \
                        "non-local party (port %s). Ignoring..."
                    logger.warning(msg % (port, address[0]))
                    continue

                # Receive the command from the server
                self.client.error = False
                command, arguments = receive(server)
                msg = r"Client on port %s received: %s %s"
                logger.debug(msg, port, command, arguments)

                # Handle special commands from the server
                if command == "__orphaned__":
                    self.client.orphaned = bool(int(arguments))

                elif command == "__error__":
                    error_status = arguments[0]
                    error_message = ''
                    if len(arguments) > 0:
                        error_message = arguments[1:]
                    logger.warning("Error status received from the server: " \
                                       "%s\n%s" % (error_status, error_message))
                    self.client.error = bool(int(error_status))
Пример #10
0
        # Start the loop to listen for commands from the Server
        logger.info("Client listening on port %i..." % self.client._port)
        try:
            while not self._finished:
                server, address = accept_no_intr(sock)

                # Reject non-local connections
                if address[0] != '127.0.0.1':
                    msg = "Client on port %s received connection from a " \
                        "non-local party (port %s). Ignoring..."
                    logger.warning(msg % (port, address[0]))
                    continue

                # Receive the command from the server
                self.client.error = False
                command, arguments = receive(server)
                msg = r"Client on port %s received: %s %s"
                logger.debug(msg, port, command, arguments)

                # Handle special commands from the server
                if command == "__orphaned__":
                    self.client.orphaned = bool(int(arguments))

                elif command == "__error__":
                    error_status = arguments[0]
                    error_message = ''
                    if len(arguments) > 0:
                        error_message = arguments[1:]
                    logger.warning("Error status received from the server: " \
                                       "%s\n%s" % (error_status, error_message))
                    self.client.error = bool(int(error_status))