Python socket 模块,MSG_DONTWAIT 实例源码

我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用socket.MSG_DONTWAIT

项目:Static-UPnP    作者:nigelb    | 项目源码 | 文件源码
def socket_handler(self, queue, running):
        self.logger = logging.getLogger("UPnPServiceResponder.schedule_handler")
        self.logger.info("PID: %s"%os.getpid())
        register_worker_signal_handler(self.logger)
        while running.value:
            try:
                ready = select.select([self.multi_sock], [], [], 10)
                for sock in ready[0]:
                    rec = sock.recvfrom(self.buffer_size, socket.MSG_DONTWAIT)
                    # Don't log packets from out IP Addresses
                    if not rec[1][0] in self.ip_addresses:
                        self.logger.debug(rec)
                    queue.put(rec)
            except socket.error as se:
                pass
            except Exception as e:
                self.logger.error(e)

        self.do_notify(b"ssdp:goodbye")
        for sock in self.socks:
            sock.close()
        self.multi_sock.close()
        self.logger.warn("Socket Handler shutting down...")
项目:Static-UPnP    作者:nigelb    | 项目源码 | 文件源码
def socket_handler(self, queue, running):
        self.logger = logging.getLogger("mDNSResponder.schedule_handler")
        self.logger.info("PID: %s" % os.getpid())
        register_worker_signal_handler(self.logger)
        while running.value:
            try:
                ready = select.select([self.multi_sock], [], [], 10)
                for sock in ready[0]:
                    rec = sock.recvfrom(self.buffer_size, socket.MSG_DONTWAIT)
                    self.logger.log(0, rec)
                    queue.put(rec)
            except socket.error as se:
                pass
            except Exception as e:
                self.logger.exception("Message")
            except KeyboardInterrupt as ki:
                time.sleep(1)

        for sock in self.socks:
            sock.close()
        self.multi_sock.close()
        self.logger.warn("Socket Handler shutting down...")
项目:BlueDot    作者:martinohanlon    | 项目源码 | 文件源码
def _read(self):
        #read until the server is stopped or the client disconnects
        while self._client_connected:
            #read data from Bluetooth socket
            try:
                data = self._client_sock.recv(1024, socket.MSG_DONTWAIT)
            except IOError as e:
                self._handle_bt_error(e)
                data = b""
            if data:
                if self._data_received_callback:
                    if self._encoding:
                        data = data.decode(self._encoding)
                    self.data_received_callback(data)
            if self._conn_thread.stopping.wait(BLUETOOTH_TIMEOUT):
                break

        #close the client socket
        self._client_sock.close()
        self._client_sock = None
        self._client_info = None
        self._client_connected = False
项目:BlueDot    作者:martinohanlon    | 项目源码 | 文件源码
def _read(self):
        #read until the client is stopped or the client disconnects
        while self._connected:
            #read data from Bluetooth socket
            try:
                data = self._client_sock.recv(1024, socket.MSG_DONTWAIT)
            except IOError as e:
                self._handle_bt_error(e)
                data = b""
            if data:
                #print("received [%s]" % data)
                if self._data_received_callback:
                    if self._encoding:
                        data = data.decode(self._encoding)
                    self.data_received_callback(data)
            if self._conn_thread.stopping.wait(BLUETOOTH_TIMEOUT):
                break
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_flags(self):
        """
        The C{flags} argument to L{send1msg} is passed on to the underlying
        C{sendmsg} call, to affect it in whatever way is defined by those
        flags.
        """
        # Just exercise one flag with simple, well-known behavior. MSG_DONTWAIT
        # makes the send a non-blocking call, even if the socket is in blocking
        # mode.  See also test_flags in RecvmsgTests
        for i in range(1024):
            try:
                send1msg(self.input.fileno(), "x" * 1024, MSG_DONTWAIT)
            except error as e:
                self.assertEqual(e.args[0], errno.EAGAIN)
                break
        else:
            self.fail(
                "Failed to fill up the send buffer, "
                "or maybe send1msg blocked for a while")
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_flags(self):
        """
        The C{flags} argument to L{sendmsg} is passed on to the underlying
        C{sendmsg} call, to affect it in whatever way is defined by those
        flags.
        """
        # Just exercise one flag with simple, well-known behavior. MSG_DONTWAIT
        # makes the send a non-blocking call, even if the socket is in blocking
        # mode.  See also test_flags in RecvmsgTests
        for i in range(1024):
            try:
                sendmsg(self.input, b"x" * 1024, flags=MSG_DONTWAIT)
            except error as e:
                self.assertEqual(e.args[0], errno.EAGAIN)
                break
        else:
            self.fail(
                "Failed to fill up the send buffer, "
                "or maybe send1msg blocked for a while")
项目:simulator    作者:P2PSP    | 项目源码 | 文件源码
def sendto(self, msg, address):
        self.lg.info("{} - [{}] -> {}".format(self.sock.getsockname(), \
                                              msg, \
                                              address))
        try:
            return self.sock.sendto(msg, socket.MSG_DONTWAIT, address + "_udp")
        except ConnectionRefusedError:
            self.lg.error("simulator_stuff.sendto: the message {} has not been delivered because the destination {} left the team".format(msg, address))
            raise
        except KeyboardInterrupt:
            self.lg.warning("simulator_stuff.sendto: send_packet {} to {}".format(msg, address))
            raise
        except FileNotFoundError:
            self.lg.error("simulator_stuff.sendto: {}".format(address + "_udp"))
            raise
        except BlockingIOError:
            raise
项目:solar    作者:mhvis    | 项目源码 | 文件源码
def __make_request(self, identifier, payload, response_id=None):
        """Directly makes a request and returns the response."""
        # Acquire socket request lock
        with self.lock:
            # Cancel a (possibly) running keep-alive timer
            self.keep_alive.cancel()
            # Receive non-blocking, to clear the receive buffer
            try:
                self.sock.recv(1024, socket.MSG_DONTWAIT)
            except socket.error as err:
                if err.errno != 11:
                    raise err
            else:
                logger.info('Receive buffer was not empty before a request')
            request = _construct_request(identifier, payload)
            self.sock.send(request)
            # Receive message, possibly retrying when wrong message arrived
            while True:
                data = self.sock.recv(1024)
                response = _tear_down_response(data)
                if not response_id or response_id == response[0]:
                    break
                else:
                    logger.info('Received unexpected message, waiting for a '
                            'new one')
            logger.debug('Request: %s', request)
            logger.debug('Response: %s', response)
            # Set keep-alive timer
            self.keep_alive = threading.Timer(keep_alive_time, self.__keep_alive)
            self.keep_alive.daemon = True
            self.keep_alive.start()
        return response
项目:packet-queue    作者:google    | 项目源码 | 文件源码
def process(self):
    """Without blocking, read available packets and invoke their callbacks."""
    data = self.socket.recv(BUFFER_SIZE, socket.MSG_DONTWAIT)
    buf = ctypes.create_string_buffer(data)
    nfq.nfq_handle_packet(self.handle, buf, len(data))
项目:igcollect    作者:innogames    | 项目源码 | 文件源码
def read_ha_proxy_stats(haproxy_stats_socket):
    conn = socket(AF_UNIX, SOCK_STREAM)
    try:
        conn.connect(haproxy_stats_socket)
        conn.sendall(b'show stat\r\n')
        data = conn.recv(BUFFER_SIZE)
        while len(data) % BUFFER_SIZE == 0:
            try:
                data += conn.recv(BUFFER_SIZE, MSG_DONTWAIT)
            except socket.error:
                break
        return data
    finally:
        conn.close()
项目:pyrocket    作者:Contraz    | 项目源码 | 文件源码
def _read(self, count, blocking=True):
        try:
            if blocking:
                data = self.sock.recv(count)
            else:
                data = self.sock.recv(count, socket.MSG_DONTWAIT)
        except BlockingIOError:
            return None

        if len(data) == 0:
            raise SocketConnError("Connection probably closed")
        return data
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def _testSendmsgTimeout(self):
        try:
            self.cli_sock.settimeout(0.03)
            with self.assertRaises(socket.timeout):
                while True:
                    self.sendmsgToServer([b"a"*512])
        finally:
            self.misc_event.set()

    # XXX: would be nice to have more tests for sendmsg flags argument.

    # Linux supports MSG_DONTWAIT when sending, but in general, it
    # only works when receiving.  Could add other platforms if they
    # support it too.
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testSendmsgDontWait(self):
        # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
        self.assertEqual(self.serv_sock.recv(512), b"a"*512)
        self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def _testSendmsgDontWait(self):
        try:
            with self.assertRaises(socket.error) as cm:
                while True:
                    self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
            self.assertIn(cm.exception.errno,
                          (errno.EAGAIN, errno.EWOULDBLOCK))
        finally:
            self.misc_event.set()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def _testSendmsgTimeout(self):
        try:
            self.cli_sock.settimeout(0.03)
            with self.assertRaises(socket.timeout):
                while True:
                    self.sendmsgToServer([b"a"*512])
        finally:
            self.misc_event.set()

    # XXX: would be nice to have more tests for sendmsg flags argument.

    # Linux supports MSG_DONTWAIT when sending, but in general, it
    # only works when receiving.  Could add other platforms if they
    # support it too.
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def testSendmsgDontWait(self):
        # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
        self.assertEqual(self.serv_sock.recv(512), b"a"*512)
        self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def _testSendmsgDontWait(self):
        try:
            with self.assertRaises(OSError) as cm:
                while True:
                    self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
            self.assertIn(cm.exception.errno,
                          (errno.EAGAIN, errno.EWOULDBLOCK))
        finally:
            self.misc_event.set()
项目:logdevourer    作者:Korbank    | 项目源码 | 文件源码
def try_readlines(self):
        try:
            while True:
                msg = self.socket.recv(4096, socket.MSG_DONTWAIT)
                yield msg.rstrip("\n")
        except socket.error, e:
            if e.errno == errno.EWOULDBLOCK or e.errno == errno.EAGAIN:
                # this is expected when there's nothing in the socket queue
                return
            else:
                raise # other error, rethrow
项目:logdevourer    作者:Korbank    | 项目源码 | 文件源码
def try_readlines(self):
        try:
            while True:
                msg = self.socket.recv(4096, socket.MSG_DONTWAIT)
                yield msg.rstrip("\n")
        except socket.error, e:
            if e.errno == errno.EWOULDBLOCK or e.errno == errno.EAGAIN:
                # this is expected when there's nothing in the socket queue
                return
            else:
                raise # other error, rethrow
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_flags(self):
        """
        The C{flags} argument to L{recv1msg} is passed on to the underlying
        C{recvmsg} call, to affect it in whatever way is defined by those
        flags.
        """
        # See test_flags in SendmsgTests
        reader, writer = socketpair(AF_UNIX)
        exc = self.assertRaises(
            error, recv1msg, reader.fileno(), MSG_DONTWAIT)
        self.assertEqual(exc.args[0], errno.EAGAIN)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def _testSendmsgTimeout(self):
        try:
            self.cli_sock.settimeout(0.03)
            with self.assertRaises(socket.timeout):
                while True:
                    self.sendmsgToServer([b"a"*512])
        finally:
            self.misc_event.set()

    # XXX: would be nice to have more tests for sendmsg flags argument.

    # Linux supports MSG_DONTWAIT when sending, but in general, it
    # only works when receiving.  Could add other platforms if they
    # support it too.
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def testSendmsgDontWait(self):
        # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
        self.assertEqual(self.serv_sock.recv(512), b"a"*512)
        self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def _testSendmsgDontWait(self):
        try:
            with self.assertRaises(OSError) as cm:
                while True:
                    self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
            self.assertIn(cm.exception.errno,
                          (errno.EAGAIN, errno.EWOULDBLOCK))
        finally:
            self.misc_event.set()
项目:mitm_relay    作者:jrmdev    | 项目源码 | 文件源码
def do_relay_tcp(client_sock, server_sock, cfg):
    server_sock.settimeout(1.0)   
    client_sock.settimeout(1.0)

    server_peer = server_sock.getpeername()
    client_peer = client_sock.getpeername()

    while True:

        # Peek for the beginnings of an ssl handshake
        try:
            packet = client_sock.recv(BUFSIZE, socket.MSG_PEEK | socket.MSG_DONTWAIT)

            if packet.startswith('\x16\x03'): # SSL/TLS Handshake.

                if not (cfg.cert and cfg.key):
                    print color("[!] SSL/TLS handshake detected, provide a server cert and key to enable interception.", 1)

                else:
                    print color('------------------ Wrapping sockets ------------------', 2)
                    client_sock = ssl.wrap_socket(client_sock, server_side=True, suppress_ragged_eofs=True, certfile=cfg.cert.name, keyfile=cfg.key.name)
                    server_sock = ssl.wrap_socket(server_sock, suppress_ragged_eofs=True)
        except:
            pass

        receiving, _, _ = select([client_sock, server_sock], [], [])


        try:
            if client_sock in receiving:
                data_out = client_sock.recv(BUFSIZE)

                if not len(data_out): # client closed connection
                    print "[+] Client disconnected", client_peer
                    client_sock.close()
                    server_sock.close()
                    break

                data_out = proxify(data_out, cfg, client_peer, server_peer, to_server=True)
                server_sock.send(data_out)

            if server_sock in receiving:
                data_in = server_sock.recv(BUFSIZE)

                if not len(data_in): # server closed connection
                    print "[+] Server disconnected", server_peer
                    client_sock.close()
                    server_sock.close()
                    break

                data_in = proxify(data_in, cfg, client_peer, server_peer, to_server=False)
                client_sock.send(data_in)

        except socket.error as e:
            print color("[!] %s" % str(e))