Python socket.send() Examples

The following are code examples for showing how to use socket.send(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: NiujiaoDebugger   Author: MrSrc   File: selector_events.py    GNU General Public License v3.0 6 votes vote down vote up
def sock_sendall(self, sock, data):
        """Send data to the socket.

        The socket must be connected to a remote socket. This method continues
        to send data from data until either all data has been sent or an
        error occurs. None is returned on success. On error, an exception is
        raised, and there is no way to determine how much data, if any, was
        successfully processed by the receiving end of the connection.
        """
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")
        fut = self.create_future()
        if data:
            self._sock_sendall(fut, None, sock, data)
        else:
            fut.set_result(None)
        return await fut 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: selector_events.py    GNU General Public License v3.0 6 votes vote down vote up
def _sock_sendall(self, fut, registered_fd, sock, data):
        if registered_fd is not None:
            self.remove_writer(registered_fd)
        if fut.cancelled():
            return

        try:
            n = sock.send(data)
        except (BlockingIOError, InterruptedError):
            n = 0
        except Exception as exc:
            fut.set_exception(exc)
            return

        if n == len(data):
            fut.set_result(None)
        else:
            if n:
                data = data[n:]
            fd = sock.fileno()
            self.add_writer(fd, self._sock_sendall, fut, fd, sock, data) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: selector_events.py    GNU General Public License v3.0 6 votes vote down vote up
def _sendto_ready(self):
        while self._buffer:
            data, addr = self._buffer.popleft()
            try:
                if self._address:
                    self._sock.send(data)
                else:
                    self._sock.sendto(data, addr)
            except (BlockingIOError, InterruptedError):
                self._buffer.appendleft((data, addr))  # Try again later.
                break
            except OSError as exc:
                self._protocol.error_received(exc)
                return
            except Exception as exc:
                self._fatal_error(
                    exc, 'Fatal write error on datagram transport')
                return

        self._maybe_resume_protocol()  # May append to buffer.
        if not self._buffer:
            self._loop._remove_writer(self._sock_fd)
            if self._closing:
                self._call_connection_lost(None) 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 6 votes vote down vote up
def testBCMConstants(self):
        socket.CAN_BCM

        # opcodes
        socket.CAN_BCM_TX_SETUP     # create (cyclic) transmission task
        socket.CAN_BCM_TX_DELETE    # remove (cyclic) transmission task
        socket.CAN_BCM_TX_READ      # read properties of (cyclic) transmission task
        socket.CAN_BCM_TX_SEND      # send one CAN frame
        socket.CAN_BCM_RX_SETUP     # create RX content filter subscription
        socket.CAN_BCM_RX_DELETE    # remove RX content filter subscription
        socket.CAN_BCM_RX_READ      # read properties of RX content filter subscription
        socket.CAN_BCM_TX_STATUS    # reply to TX_READ request
        socket.CAN_BCM_TX_EXPIRED   # notification on performed transmissions (count=0)
        socket.CAN_BCM_RX_STATUS    # reply to RX_READ request
        socket.CAN_BCM_RX_TIMEOUT   # cyclic message is absent
        socket.CAN_BCM_RX_CHANGED   # updated CAN frame (detected content change) 
Example 5
Project: NiujiaoDebugger   Author: MrSrc   File: test_proactor_events.py    GNU General Public License v3.0 6 votes vote down vote up
def test_loop_writing_err(self, m_log):
        err = self.loop._proactor.send.side_effect = OSError()
        tr = self.socket_transport()
        tr._fatal_error = mock.Mock()
        tr._buffer = [b'da', b'ta']
        tr._loop_writing()
        tr._fatal_error.assert_called_with(
                            err,
                            'Fatal write error on pipe transport')
        tr._conn_lost = 1

        tr.write(b'data')
        tr.write(b'data')
        tr.write(b'data')
        tr.write(b'data')
        tr.write(b'data')
        self.assertEqual(tr._buffer, None)
        m_log.warning.assert_called_with('socket.send() raised exception.') 
Example 6
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSendAfterClose(self):
        # testing send() after close() with timeout
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        sock.close()
        self.assertRaises(socket.error, sock.send, "spam") 
Example 7
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testRecv(self):
        self.serv_conn.send(MSG) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testOverFlowRecv(self):
        self.serv_conn.send(MSG) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testRecvFrom(self):
        self.serv_conn.send(MSG) 
Example 10
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testOverFlowRecvFrom(self):
        self.serv_conn.send(MSG) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testDup(self):
        self.serv_conn.send(MSG) 
Example 12
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testShutdown(self):
        self.serv_conn.send(MSG)
        self.serv_conn.shutdown(2) 
Example 13
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testShutdown_overflow(self):
        import _testcapi
        self.serv_conn.send(MSG)
        # Issue 15989
        self.assertRaises(OverflowError, self.serv_conn.shutdown,
                          _testcapi.INT_MAX + 1)
        self.assertRaises(OverflowError, self.serv_conn.shutdown,
                          2 + (_testcapi.UINT_MAX + 1))
        self.serv_conn.shutdown(2) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testRecv(self):
        self.cli.send(MSG) 
Example 15
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSend(self):
        self.serv.send(MSG) 
Example 16
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def send(self, data, flags=0):
            n = self._sock.send(data, flags)
            self.sent.append(data[:n])
            return n 
Example 17
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInsideTimeout(self):
        conn, addr = self.serv.accept()
        self.addCleanup(conn.close)
        time.sleep(3)
        conn.send("done!") 
Example 18
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testRecvIntoArray(self):
        with test_support.check_py3k_warnings():
            buf = buffer(MSG)
        self.serv_conn.send(buf) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testRecvFromIntoArray(self):
        with test_support.check_py3k_warnings():
            buf = buffer(MSG)
        self.serv_conn.send(buf) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testRecvFromIntoSmallBuffer(self):
        with test_support.check_py3k_warnings():
            buf = buffer(MSG)
        self.serv_conn.send(buf) 
Example 21
Project: Python-examples   Author: tuxfux-hlp   File: chat_server.py    GNU General Public License v2.0 5 votes vote down vote up
def broadcast_data (sock, message):
    #Do not send the message to master socket and the client who has send us the message
    for socket in CONNECTION_LIST:
        if socket != server_socket and socket != sock :
            try :
                socket.send(message)
            except :
                # broken socket connection may be, chat client pressed ctrl+c for example
                socket.close()
                CONNECTION_LIST.remove(socket) 
Example 22
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: test_jyserver.py    MIT License 5 votes vote down vote up
def send_kill_msg(self, socket):
        socket.send(pycompletionserver.MSG_KILL_SERVER)




# Run for jython in command line:
# c:\bin\jython2.7.0\bin\jython.exe -m py.test tests\test_jyserver.py 
Example 23
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: test_pyserver.py    MIT License 5 votes vote down vote up
def send(s, msg):
            s.send(msg) 
Example 24
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: test_pyserver.py    MIT License 5 votes vote down vote up
def send(s, msg):
            s.send(bytearray(msg, 'utf-8')) 
Example 25
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: test_pyserver.py    MIT License 5 votes vote down vote up
def send_kill_msg(self, socket):
        socket.send(pycompletionserver.MSG_KILL_SERVER) 
Example 26
Project: ISO8583-Simulator   Author: bassrehab   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def broadcast_data(self, sock, message):
        """Send broadcast message to all clients other than the
           server socket and the client socket from which the data is received."""

        for socket in self.CONNECTION_LIST:
            if socket != self.server_socket and socket != sock:
                socket.send(message) 
Example 27
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def write_to_fd(self, data):
        return self.socket.send(data) 
Example 28
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def write_to_fd(self, data):
        try:
            return self.socket.send(data)
        except ssl.SSLError as e:
            if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
                # the socket is not writeable; we need to transform this into
                # an EWOULDBLOCK socket.error or a zero return value,
                # either of which will be recognized by the caller of this
                # method. Prior to Python 3.5, an unwriteable socket would
                # simply return 0 bytes written.
                return 0
            raise 
Example 29
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def write_to_fd(self, data):
        return self.socket.send(data) 
Example 30
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 5 votes vote down vote up
def write_to_fd(self, data):
        try:
            return self.socket.send(data)
        except ssl.SSLError as e:
            if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
                # the socket is not writeable; we need to transform this into
                # an EWOULDBLOCK socket.error or a zero return value,
                # either of which will be recognized by the caller of this
                # method. Prior to Python 3.5, an unwriteable socket would
                # simply return 0 bytes written.
                return 0
            raise 
Example 31
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 5 votes vote down vote up
def write_to_fd(self, data):
        return self.socket.send(data) 
Example 32
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 5 votes vote down vote up
def write_to_fd(self, data):
        try:
            return self.socket.send(data)
        except ssl.SSLError as e:
            if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
                # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
                # the socket is not writeable; we need to transform this into
                # an EWOULDBLOCK socket.error or a zero return value,
                # either of which will be recognized by the caller of this
                # method. Prior to Python 3.5, an unwriteable socket would
                # simply return 0 bytes written.
                return 0
            raise 
Example 33
Project: esys-pbi   Author: fsxfreak   File: pupil_remote.py    MIT License 5 votes vote down vote up
def thread_loop(self, context, pipe):
        poller = zmq.Poller()
        ipc_pub = zmq_tools.Msg_Dispatcher(context, self.g_pool.ipc_push_url)
        poller.register(pipe, zmq.POLLIN)
        remote_socket = None

        while True:
            items = dict(poller.poll())
            if pipe in items:
                cmd = pipe.recv_string()
                if cmd == 'Exit':
                    break
                elif cmd == 'Bind':
                    new_url = pipe.recv_string()
                    if remote_socket:
                        poller.unregister(remote_socket)
                        remote_socket.close(linger=0)
                    try:
                        remote_socket = context.socket(zmq.REP)
                        remote_socket.bind(new_url)
                    except zmq.ZMQError as e:
                        remote_socket = None
                        pipe.send_string("Error", flags=zmq.SNDMORE)
                        pipe.send_string("Could not bind to Socket: {}. Reason: {}".format(new_url, e))
                    else:
                        pipe.send_string("Bind OK", flags=zmq.SNDMORE)
                        # `.last_endpoint` is already of type `bytes`
                        pipe.send(remote_socket.last_endpoint.replace(b"tcp://", b""))
                        poller.register(remote_socket, zmq.POLLIN)
            if remote_socket in items:
                self.on_recv(remote_socket, ipc_pub)

        self.thread_pipe = None 
Example 34
Project: esys-pbi   Author: fsxfreak   File: pupil_remote.py    MIT License 5 votes vote down vote up
def on_notify(self, notification):
        """send simple string messages to control application functions.

        Emits notifications:
            ``recording.should_start``
            ``recording.should_stop``
            ``calibration.should_start``
            ``calibration.should_stop``
            Any other notification received though the reqrepl port.
        """
        pass 
Example 35
Project: NiujiaoDebugger   Author: MrSrc   File: proactor_events.py    GNU General Public License v3.0 5 votes vote down vote up
def write(self, data):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError(
                f"data argument must be a bytes-like object, "
                f"not {type(data).__name__}")
        if self._eof_written:
            raise RuntimeError('write_eof() already called')
        if self._empty_waiter is not None:
            raise RuntimeError('unable to write; sendfile is in progress')

        if not data:
            return

        if self._conn_lost:
            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
                logger.warning('socket.send() raised exception.')
            self._conn_lost += 1
            return

        # Observable states:
        # 1. IDLE: _write_fut and _buffer both None
        # 2. WRITING: _write_fut set; _buffer None
        # 3. BACKED UP: _write_fut set; _buffer a bytearray
        # We always copy the data, so the caller can't modify it
        # while we're still waiting for the I/O to happen.
        if self._write_fut is None:  # IDLE -> WRITING
            assert self._buffer is None
            # Pass a copy, except if it's already immutable.
            self._loop_writing(data=bytes(data))
        elif not self._buffer:  # WRITING -> BACKED UP
            # Make a mutable copy which we can extend.
            self._buffer = bytearray(data)
            self._maybe_pause_protocol()
        else:  # BACKED UP
            # Append to buffer (also copies).
            self._buffer.extend(data)
            self._maybe_pause_protocol() 
Example 36
Project: NiujiaoDebugger   Author: MrSrc   File: proactor_events.py    GNU General Public License v3.0 5 votes vote down vote up
def _loop_writing(self, f=None, data=None):
        try:
            if f is not None and self._write_fut is None and self._closing:
                # XXX most likely self._force_close() has been called, and
                # it has set self._write_fut to None.
                return
            assert f is self._write_fut
            self._write_fut = None
            self._pending_write = 0
            if f:
                f.result()
            if data is None:
                data = self._buffer
                self._buffer = None
            if not data:
                if self._closing:
                    self._loop.call_soon(self._call_connection_lost, None)
                if self._eof_written:
                    self._sock.shutdown(socket.SHUT_WR)
                # Now that we've reduced the buffer size, tell the
                # protocol to resume writing if it was paused.  Note that
                # we do this last since the callback is called immediately
                # and it may add more data to the buffer (even causing the
                # protocol to be paused again).
                self._maybe_resume_protocol()
            else:
                self._write_fut = self._loop._proactor.send(self._sock, data)
                if not self._write_fut.done():
                    assert self._pending_write == 0
                    self._pending_write = len(data)
                    self._write_fut.add_done_callback(self._loop_writing)
                    self._maybe_pause_protocol()
                else:
                    self._write_fut.add_done_callback(self._loop_writing)
            if self._empty_waiter is not None and self._write_fut is None:
                self._empty_waiter.set_result(None)
        except ConnectionResetError as exc:
            self._force_close(exc)
        except OSError as exc:
            self._fatal_error(exc, 'Fatal write error on pipe transport') 
Example 37
Project: NiujiaoDebugger   Author: MrSrc   File: proactor_events.py    GNU General Public License v3.0 5 votes vote down vote up
def sock_sendall(self, sock, data):
        return await self._proactor.send(sock, data) 
Example 38
Project: NiujiaoDebugger   Author: MrSrc   File: proactor_events.py    GNU General Public License v3.0 5 votes vote down vote up
def _write_to_self(self):
        self._csock.send(b'\0') 
Example 39
Project: NiujiaoDebugger   Author: MrSrc   File: selector_events.py    GNU General Public License v3.0 5 votes vote down vote up
def _write_to_self(self):
        # This may be called from a different thread, possibly after
        # _close_self_pipe() has been called or even while it is
        # running.  Guard for self._csock being None or closed.  When
        # a socket is closed, send() raises OSError (with errno set to
        # EBADF, but let's not rely on the exact error code).
        csock = self._csock
        if csock is not None:
            try:
                csock.send(b'\0')
            except OSError:
                if self._debug:
                    logger.debug("Fail to write a null byte into the "
                                 "self-pipe socket",
                                 exc_info=True) 
Example 40
Project: NiujiaoDebugger   Author: MrSrc   File: selector_events.py    GNU General Public License v3.0 5 votes vote down vote up
def sock_accept(self, sock):
        """Accept a connection.

        The socket must be bound to an address and listening for connections.
        The return value is a pair (conn, address) where conn is a new socket
        object usable to send and receive data on the connection, and address
        is the address bound to the socket on the other end of the connection.
        """
        if self._debug and sock.gettimeout() != 0:
            raise ValueError("the socket must be non-blocking")
        fut = self.create_future()
        self._sock_accept(fut, False, sock)
        return await fut 
Example 41
Project: NiujiaoDebugger   Author: MrSrc   File: selector_events.py    GNU General Public License v3.0 5 votes vote down vote up
def write(self, data):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError(f'data argument must be a bytes-like object, '
                            f'not {type(data).__name__!r}')
        if self._eof:
            raise RuntimeError('Cannot call write() after write_eof()')
        if self._empty_waiter is not None:
            raise RuntimeError('unable to write; sendfile is in progress')
        if not data:
            return

        if self._conn_lost:
            if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
                logger.warning('socket.send() raised exception.')
            self._conn_lost += 1
            return

        if not self._buffer:
            # Optimization: try to send now.
            try:
                n = self._sock.send(data)
            except (BlockingIOError, InterruptedError):
                pass
            except Exception as exc:
                self._fatal_error(exc, 'Fatal write error on socket transport')
                return
            else:
                data = data[n:]
                if not data:
                    return
            # Not all was written; register write handler.
            self._loop._add_writer(self._sock_fd, self._write_ready)

        # Add it to the buffer.
        self._buffer.extend(data)
        self._maybe_pause_protocol() 
Example 42
Project: NiujiaoDebugger   Author: MrSrc   File: selector_events.py    GNU General Public License v3.0 5 votes vote down vote up
def _write_ready(self):
        assert self._buffer, 'Data should not be empty'

        if self._conn_lost:
            return
        try:
            n = self._sock.send(self._buffer)
        except (BlockingIOError, InterruptedError):
            pass
        except Exception as exc:
            self._loop._remove_writer(self._sock_fd)
            self._buffer.clear()
            self._fatal_error(exc, 'Fatal write error on socket transport')
            if self._empty_waiter is not None:
                self._empty_waiter.set_exception(exc)
        else:
            if n:
                del self._buffer[:n]
            self._maybe_resume_protocol()  # May append to buffer.
            if not self._buffer:
                self._loop._remove_writer(self._sock_fd)
                if self._empty_waiter is not None:
                    self._empty_waiter.set_result(None)
                if self._closing:
                    self._call_connection_lost(None)
                elif self._eof:
                    self._sock.shutdown(socket.SHUT_WR) 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def clientSetUp(self):
        self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
        try:
            # RDS sockets must be bound explicitly to send or receive data
            self.cli.bind((HOST, 0))
            self.cli_addr = self.cli.getsockname()
        except OSError:
            # skipTest should not be called here, and will be called in the
            # server instead
            pass 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testStream(self):
        self.cli.send(MSG)
        self.cli.close() 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testSendAfterClose(self):
        # testing send() after close() with timeout
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        sock.close()
        self.assertRaises(OSError, sock.send, b"spam") 
Example 46
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testSendMaxFrame(self):
        self.cf = self.build_can_frame(0x00, b'\x07' * 8)
        self.cli.send(self.cf) 
Example 47
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testSendMultiFrames(self):
        self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
        self.cli.send(self.cf1)

        self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
        self.cli.send(self.cf2) 
Example 48
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testBCM(self):
        bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
        self.addCleanup(bcm.close)
        bcm.connect((self.interface,))
        self.can_id = 0x123
        self.data = bytes([0xc0, 0xff, 0xee])
        self.cf = self.build_can_frame(self.can_id, self.data)
        opcode = socket.CAN_BCM_TX_SEND
        flags = 0
        count = 0
        ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0
        bcm_can_id = 0x0222
        nframes = 1
        assert len(self.cf) == 16
        header = struct.pack(self.bcm_cmd_msg_fmt,
                    opcode,
                    flags,
                    count,
                    ival1_seconds,
                    ival1_usec,
                    ival2_seconds,
                    ival2_usec,
                    bcm_can_id,
                    nframes,
                    )
        header_plus_frame = header + self.cf
        bytes_sent = bcm.send(header_plus_frame)
        self.assertEqual(bytes_sent, len(header_plus_frame)) 
Example 49
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testRecv(self):
        self.serv_conn.send(MSG) 
Example 50
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testOverFlowRecv(self):
        self.serv_conn.send(MSG) 
Example 51
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testOverFlowRecvFrom(self):
        self.serv_conn.send(MSG) 
Example 52
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testFromFd(self):
        self.serv_conn.send(MSG) 
Example 53
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testDup(self):
        self.serv_conn.send(MSG) 
Example 54
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testShutdown(self):
        self.serv_conn.send(MSG)
        self.serv_conn.shutdown(2) 
Example 55
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testShutdown_overflow(self):
        import _testcapi
        self.serv_conn.send(MSG)
        # Issue 15989
        self.assertRaises(OverflowError, self.serv_conn.shutdown,
                          _testcapi.INT_MAX + 1)
        self.assertRaises(OverflowError, self.serv_conn.shutdown,
                          2 + (_testcapi.UINT_MAX + 1))
        self.serv_conn.shutdown(2) 
Example 56
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def sendToServer(self, msg):
        # Send msg to the server.
        return self.cli_sock.send(msg)

    # Tuple of alternative default arguments for sendmsg() when called
    # via sendmsgToServer() (e.g. to include a destination address). 
Example 57
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testSendmsgExcessCmsgReject(self):
        if not hasattr(socket, "CMSG_SPACE"):
            # Can only send one item
            with self.assertRaises(OSError) as cm:
                self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
            self.assertIsNone(cm.exception.errno)
        self.sendToServer(b"done") 
Example 58
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def sendAncillaryIfPossible(self, msg, ancdata):
        # Try to send msg and ancdata to server, but if the system
        # call fails, just send msg with no ancillary data.
        try:
            nbytes = self.sendmsgToServer([msg], ancdata)
        except OSError as e:
            # Check that it was the system call that failed
            self.assertIsInstance(e.errno, int)
            nbytes = self.sendmsgToServer([msg])
        self.assertEqual(nbytes, len(msg)) 
Example 59
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testOddCmsgSize(self):
        # Try to send ancillary data with first item one byte too
        # long.  Fall back to sending with correct size if this fails,
        # and check that second item was handled correctly.
        self.checkTrafficClassAndHopLimit(ancbufsize=10240,
                                          maxhop=self.hop_limit) 
Example 60
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testInterruptedSendTimeout(self):
        self.checkInterruptedSend(self.serv_conn.send, b"a"*512) 
Example 61
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testSend(self):
        self.serv.send(MSG) 
Example 62
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testInheritFlags(self):
        time.sleep(0.1)
        self.cli.connect((HOST, self.port))
        time.sleep(0.5)
        self.cli.send(MSG) 
Example 63
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testRecv(self):
        # Testing non-blocking recv
        conn, addr = self.serv.accept()
        self.addCleanup(conn.close)
        conn.setblocking(0)

        # the server didn't send data yet: non-blocking recv() fails
        with self.assertRaises(BlockingIOError):
            msg = conn.recv(len(MSG))

        self.event.set()

        read, write, err = select.select([conn], [], [], MAIN_TIMEOUT)
        if conn not in read:
            self.fail("Error during select call to non-blocking socket.")

        # the server sent data yet: non-blocking recv() doesn't block
        msg = conn.recv(len(MSG))
        self.assertEqual(msg, MSG) 
Example 64
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testRecv(self):
        self.cli.connect((HOST, self.port))

        # don't send anything before event is set to check
        # that non-blocking recv() raises BlockingIOError
        self.event.wait()

        # send data: recv() will no longer block
        self.cli.sendall(MSG) 
Example 65
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testInsideTimeout(self):
        conn, addr = self.serv.accept()
        self.addCleanup(conn.close)
        time.sleep(3)
        conn.send(b"done!") 
Example 66
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testRecvFromIntoArray(self):
        buf = bytes(MSG)
        self.serv_conn.send(buf) 
Example 67
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testRecvFromIntoSmallBuffer(self):
        self.serv_conn.send(MSG) 
Example 68
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def _testStream(self):
        self.cli.send(MSG)
        self.cli.close() 
Example 69
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def testShare(self):
        # Transfer the listening server socket to another process
        # and service it from there.

        # Create process:
        q = multiprocessing.Queue()
        p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,))
        p.start()

        # Get the shared socket data
        data = self.serv.share(p.pid)

        # Pass the shared socket to the other process
        addr = self.serv.getsockname()
        self.serv.close()
        q.put(data)

        # The data that the server will send us
        message = b"slapmahfro"
        q.put(message)

        # Connect
        s = socket.create_connection(addr)
        #  listen for the data
        m = []
        while True:
            data = s.recv(100)
            if not data:
                break
            m.append(data)
        s.close()
        received = b"".join(m)
        self.assertEqual(received, message)
        p.join() 
Example 70
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def meth_from_sock(self, sock):
        # Depending on the mixin class being run return either send()
        # or sendfile() method implementation.
        return getattr(sock, "_sendfile_use_send")

    # regular file 
Example 71
Project: NiujiaoDebugger   Author: MrSrc   File: test_proactor_events.py    GNU General Public License v3.0 5 votes vote down vote up
def test_loop_writing(self):
        tr = self.socket_transport()
        tr._buffer = bytearray(b'data')
        tr._loop_writing()
        self.loop._proactor.send.assert_called_with(self.sock, b'data')
        self.loop._proactor.send.return_value.add_done_callback.\
            assert_called_with(tr._loop_writing) 
Example 72
Project: NiujiaoDebugger   Author: MrSrc   File: test_proactor_events.py    GNU General Public License v3.0 5 votes vote down vote up
def test_loop_writing_force_close(self):
        exc_handler = mock.Mock()
        self.loop.set_exception_handler(exc_handler)
        fut = asyncio.Future(loop=self.loop)
        fut.set_result(1)
        self.proactor.send.return_value = fut

        tr = self.socket_transport()
        tr.write(b'data')
        tr._force_close(None)
        test_utils.run_briefly(self.loop)
        exc_handler.assert_not_called() 
Example 73
Project: NiujiaoDebugger   Author: MrSrc   File: test_proactor_events.py    GNU General Public License v3.0 5 votes vote down vote up
def test_write_eof_buffer(self):
        tr = self.socket_transport()
        f = asyncio.Future(loop=self.loop)
        tr._loop._proactor.send.return_value = f
        tr.write(b'data')
        tr.write_eof()
        self.assertTrue(tr._eof_written)
        self.assertFalse(self.sock.shutdown.called)
        tr._loop._proactor.send.assert_called_with(self.sock, b'data')
        f.set_result(4)
        self.loop._run_once()
        self.sock.shutdown.assert_called_with(socket.SHUT_WR)
        tr.close() 
Example 74
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: test_jyserver.py    MIT License 4 votes vote down vote up
def test_completion_sockets_and_messages(self):
        dbg('test_completion_sockets_and_messages')
        t, socket = self.create_connections()
        self.socket = socket
        dbg('connections created')

        try:
            #now that we have the connections all set up, check the code completion messages.
            msg = urllib.quote_plus('math')

            toWrite = '@@IMPORTS:%sEND@@' % msg
            dbg('writing' + str(toWrite))
            socket.send(toWrite)  #math completions
            completions = self.read_msg()
            dbg(urllib.unquote_plus(completions))

            start = '@@COMPLETIONS('
            self.assertTrue(completions.startswith(start), '%s DOESNT START WITH %s' % (completions, start))
            self.assertTrue(completions.find('@@COMPLETIONS') != -1)
            self.assertTrue(completions.find('END@@') != -1)


            msg = urllib.quote_plus('__builtin__.str')
            toWrite = '@@IMPORTS:%sEND@@' % msg
            dbg('writing' + str(toWrite))
            socket.send(toWrite)  #math completions
            completions = self.read_msg()
            dbg(urllib.unquote_plus(completions))

            start = '@@COMPLETIONS('
            self.assertTrue(completions.startswith(start), '%s DOESNT START WITH %s' % (completions, start))
            self.assertTrue(completions.find('@@COMPLETIONS') != -1)
            self.assertTrue(completions.find('END@@') != -1)



        finally:
            try:
                self.send_kill_msg(socket)


                while not t.ended:
                    pass  #wait until it receives the message and quits.


                socket.close()
            except:
                pass 
Example 75
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 4 votes vote down vote up
def write(self, data, callback=None):
        """Asynchronously write the given data to this stream.

        If ``callback`` is given, we call it when all of the buffered write
        data has been successfully written to the stream. If there was
        previously buffered write data and an old write callback, that
        callback is simply overwritten with this new callback.

        If no ``callback`` is given, this method returns a `.Future` that
        resolves (with a result of ``None``) when the write has been
        completed.  If `write` is called again before that `.Future` has
        resolved, the previous future will be orphaned and will never resolve.

        .. versionchanged:: 4.0
            Now returns a `.Future` if no callback is given.
        """
        assert isinstance(data, bytes)
        self._check_closed()
        # We use bool(_write_buffer) as a proxy for write_buffer_size>0,
        # so never put empty strings in the buffer.
        if data:
            if (self.max_write_buffer_size is not None and
                    self._write_buffer_size + len(data) > self.max_write_buffer_size):
                raise StreamBufferFullError("Reached maximum write buffer size")
            # Break up large contiguous strings before inserting them in the
            # write buffer, so we don't have to recopy the entire thing
            # as we slice off pieces to send to the socket.
            WRITE_BUFFER_CHUNK_SIZE = 128 * 1024
            for i in range(0, len(data), WRITE_BUFFER_CHUNK_SIZE):
                self._write_buffer.append(data[i:i + WRITE_BUFFER_CHUNK_SIZE])
            self._write_buffer_size += len(data)
        if callback is not None:
            self._write_callback = stack_context.wrap(callback)
            future = None
        else:
            future = self._write_future = TracebackFuture()
            future.add_done_callback(lambda f: f.exception())
        if not self._connecting:
            self._handle_write()
            if self._write_buffer:
                self._add_io_state(self.io_loop.WRITE)
            self._maybe_add_error_listener()
        return future 
Example 76
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 4 votes vote down vote up
def _handle_write(self):
        while self._write_buffer:
            try:
                if not self._write_buffer_frozen:
                    # On windows, socket.send blows up if given a
                    # write buffer that's too large, instead of just
                    # returning the number of bytes it was able to
                    # process.  Therefore we must not call socket.send
                    # with more than 128KB at a time.
                    _merge_prefix(self._write_buffer, 128 * 1024)
                num_bytes = self.write_to_fd(self._write_buffer[0])
                if num_bytes == 0:
                    # With OpenSSL, if we couldn't write the entire buffer,
                    # the very same string object must be used on the
                    # next call to send.  Therefore we suppress
                    # merging the write buffer after an incomplete send.
                    # A cleaner solution would be to set
                    # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, but this is
                    # not yet accessible from python
                    # (http://bugs.python.org/issue8240)
                    self._write_buffer_frozen = True
                    break
                self._write_buffer_frozen = False
                _merge_prefix(self._write_buffer, num_bytes)
                self._write_buffer.popleft()
                self._write_buffer_size -= num_bytes
            except (socket.error, IOError, OSError) as e:
                if e.args[0] in _ERRNO_WOULDBLOCK:
                    self._write_buffer_frozen = True
                    break
                else:
                    if not self._is_connreset(e):
                        # Broken pipe errors are usually caused by connection
                        # reset, and its better to not log EPIPE errors to
                        # minimize log spam
                        gen_log.warning("Write error on %s: %s",
                                        self.fileno(), e)
                    self.close(exc_info=True)
                    return
        if not self._write_buffer:
            if self._write_callback:
                callback = self._write_callback
                self._write_callback = None
                self._run_callback(callback)
            if self._write_future:
                future = self._write_future
                self._write_future = None
                future.set_result(None) 
Example 77
Project: tornado-zh   Author: tao12345666333   File: iostream.py    MIT License 4 votes vote down vote up
def write(self, data, callback=None):
        """Asynchronously write the given data to this stream.

        If ``callback`` is given, we call it when all of the buffered write
        data has been successfully written to the stream. If there was
        previously buffered write data and an old write callback, that
        callback is simply overwritten with this new callback.

        If no ``callback`` is given, this method returns a `.Future` that
        resolves (with a result of ``None``) when the write has been
        completed.  If `write` is called again before that `.Future` has
        resolved, the previous future will be orphaned and will never resolve.

        .. versionchanged:: 4.0
            Now returns a `.Future` if no callback is given.
        """
        assert isinstance(data, bytes)
        self._check_closed()
        # We use bool(_write_buffer) as a proxy for write_buffer_size>0,
        # so never put empty strings in the buffer.
        if data:
            if (self.max_write_buffer_size is not None and
                    self._write_buffer_size + len(data) > self.max_write_buffer_size):
                raise StreamBufferFullError("Reached maximum write buffer size")
            # Break up large contiguous strings before inserting them in the
            # write buffer, so we don't have to recopy the entire thing
            # as we slice off pieces to send to the socket.
            WRITE_BUFFER_CHUNK_SIZE = 128 * 1024
            for i in range(0, len(data), WRITE_BUFFER_CHUNK_SIZE):
                self._write_buffer.append(data[i:i + WRITE_BUFFER_CHUNK_SIZE])
            self._write_buffer_size += len(data)
        if callback is not None:
            self._write_callback = stack_context.wrap(callback)
            future = None
        else:
            future = self._write_future = TracebackFuture()
            future.add_done_callback(lambda f: f.exception())
        if not self._connecting:
            self._handle_write()
            if self._write_buffer:
                self._add_io_state(self.io_loop.WRITE)
            self._maybe_add_error_listener()
        return future 
Example 78
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 4 votes vote down vote up
def write(self, data, callback=None):
        """Asynchronously write the given data to this stream.

        If ``callback`` is given, we call it when all of the buffered write
        data has been successfully written to the stream. If there was
        previously buffered write data and an old write callback, that
        callback is simply overwritten with this new callback.

        If no ``callback`` is given, this method returns a `.Future` that
        resolves (with a result of ``None``) when the write has been
        completed.  If `write` is called again before that `.Future` has
        resolved, the previous future will be orphaned and will never resolve.

        .. versionchanged:: 4.0
            Now returns a `.Future` if no callback is given.
        """
        assert isinstance(data, bytes)
        self._check_closed()
        # We use bool(_write_buffer) as a proxy for write_buffer_size>0,
        # so never put empty strings in the buffer.
        if data:
            if (self.max_write_buffer_size is not None and
                    self._write_buffer_size + len(data) > self.max_write_buffer_size):
                raise StreamBufferFullError("Reached maximum write buffer size")
            # Break up large contiguous strings before inserting them in the
            # write buffer, so we don't have to recopy the entire thing
            # as we slice off pieces to send to the socket.
            WRITE_BUFFER_CHUNK_SIZE = 128 * 1024
            for i in range(0, len(data), WRITE_BUFFER_CHUNK_SIZE):
                self._write_buffer.append(data[i:i + WRITE_BUFFER_CHUNK_SIZE])
            self._write_buffer_size += len(data)
        if callback is not None:
            self._write_callback = stack_context.wrap(callback)
            future = None
        else:
            future = self._write_future = TracebackFuture()
            future.add_done_callback(lambda f: f.exception())
        if not self._connecting:
            self._handle_write()
            if self._write_buffer:
                self._add_io_state(self.io_loop.WRITE)
            self._maybe_add_error_listener()
        return future 
Example 79
Project: TornadoWeb   Author: VxCoder   File: iostream.py    Apache License 2.0 4 votes vote down vote up
def _handle_write(self):
        while self._write_buffer:
            try:
                if not self._write_buffer_frozen:
                    # On windows, socket.send blows up if given a
                    # write buffer that's too large, instead of just
                    # returning the number of bytes it was able to
                    # process.  Therefore we must not call socket.send
                    # with more than 128KB at a time.
                    _merge_prefix(self._write_buffer, 128 * 1024)
                num_bytes = self.write_to_fd(self._write_buffer[0])
                if num_bytes == 0:
                    # With OpenSSL, if we couldn't write the entire buffer,
                    # the very same string object must be used on the
                    # next call to send.  Therefore we suppress
                    # merging the write buffer after an incomplete send.
                    # A cleaner solution would be to set
                    # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, but this is
                    # not yet accessible from python
                    # (http://bugs.python.org/issue8240)
                    self._write_buffer_frozen = True
                    break
                self._write_buffer_frozen = False
                _merge_prefix(self._write_buffer, num_bytes)
                self._write_buffer.popleft()
                self._write_buffer_size -= num_bytes
            except (socket.error, IOError, OSError) as e:
                if e.args[0] in _ERRNO_WOULDBLOCK:
                    self._write_buffer_frozen = True
                    break
                else:
                    if not self._is_connreset(e):
                        # Broken pipe errors are usually caused by connection
                        # reset, and its better to not log EPIPE errors to
                        # minimize log spam
                        gen_log.warning("Write error on %s: %s",
                                        self.fileno(), e)
                    self.close(exc_info=True)
                    return
        if not self._write_buffer:
            if self._write_callback:
                callback = self._write_callback
                self._write_callback = None
                self._run_callback(callback)
            if self._write_future:
                future = self._write_future
                self._write_future = None
                future.set_result(None) 
Example 80
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 4 votes vote down vote up
def test_aead_aes_gcm(self):
        key = bytes.fromhex('c939cc13397c1d37de6ae0e1cb7c423c')
        iv = bytes.fromhex('b3d8cc017cbb89b39e0f67e2')
        plain = bytes.fromhex('c3b3c41f113a31b73d9a5cd432103069')
        assoc = bytes.fromhex('24825602bd12a984e0092d3e448eda5f')
        expected_ct = bytes.fromhex('93fe7d9e9bfd10348a5606e5cafa7354')
        expected_tag = bytes.fromhex('0032a1dc85f1c9786925a2e71d8272dd')

        taglen = len(expected_tag)
        assoclen = len(assoc)

        with self.create_alg('aead', 'gcm(aes)') as algo:
            algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key)
            algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_AEAD_AUTHSIZE,
                            None, taglen)

            # send assoc, plain and tag buffer in separate steps
            op, _ = algo.accept()
            with op:
                op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv,
                                 assoclen=assoclen, flags=socket.MSG_MORE)
                op.sendall(assoc, socket.MSG_MORE)
                op.sendall(plain)
                res = op.recv(assoclen + len(plain) + taglen)
                self.assertEqual(expected_ct, res[assoclen:-taglen])
                self.assertEqual(expected_tag, res[-taglen:])

            # now with msg
            op, _ = algo.accept()
            with op:
                msg = assoc + plain
                op.sendmsg_afalg([msg], op=socket.ALG_OP_ENCRYPT, iv=iv,
                                 assoclen=assoclen)
                res = op.recv(assoclen + len(plain) + taglen)
                self.assertEqual(expected_ct, res[assoclen:-taglen])
                self.assertEqual(expected_tag, res[-taglen:])

            # create anc data manually
            pack_uint32 = struct.Struct('I').pack
            op, _ = algo.accept()
            with op:
                msg = assoc + plain
                op.sendmsg(
                    [msg],
                    ([socket.SOL_ALG, socket.ALG_SET_OP, pack_uint32(socket.ALG_OP_ENCRYPT)],
                     [socket.SOL_ALG, socket.ALG_SET_IV, pack_uint32(len(iv)) + iv],
                     [socket.SOL_ALG, socket.ALG_SET_AEAD_ASSOCLEN, pack_uint32(assoclen)],
                    )
                )
                res = op.recv(len(msg) + taglen)
                self.assertEqual(expected_ct, res[assoclen:-taglen])
                self.assertEqual(expected_tag, res[-taglen:])

            # decrypt and verify
            op, _ = algo.accept()
            with op:
                msg = assoc + expected_ct + expected_tag
                op.sendmsg_afalg([msg], op=socket.ALG_OP_DECRYPT, iv=iv,
                                 assoclen=assoclen)
                res = op.recv(len(msg) - taglen)
                self.assertEqual(plain, res[assoclen:])