我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用socket.MSG_DONTWAIT。
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...")
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...")
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
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
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")
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")
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
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
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))
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()
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
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.
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))
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()
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()
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
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)
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))