Python socket.send() Examples

The following are 30 code examples of socket.send(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: mtprotoproxy.py    From mtprotoproxy with MIT License 6 votes vote down vote up
def write(self, data, extra={}):
        SMALL_PKT_BORDER = 0x7f
        LARGE_PKT_BORGER = 256 ** 3

        if len(data) % 4 != 0:
            print_err("BUG: MTProtoFrameStreamWriter attempted to send msg with len", len(data))
            return 0

        if extra.get("SIMPLE_ACK"):
            return self.upstream.write(data[::-1])

        len_div_four = len(data) // 4

        if len_div_four < SMALL_PKT_BORDER:
            return self.upstream.write(bytes([len_div_four]) + data)
        elif len_div_four < LARGE_PKT_BORGER:
            return self.upstream.write(b'\x7f' + int.to_bytes(len_div_four, 3, 'little') + data)
        else:
            print_err("Attempted to send too large pkt len =", len(data))
            return 0 
Example #2
Source File: ht_proxy_if.py    From hometop_HT3 with GNU General Public License v3.0 6 votes vote down vote up
def __waitfor_client_register(self):
        self.request.settimeout(5)
        try:
            devicetypetmp=self.request.recv(20)
            self._client_devicetype = devicetypetmp.decode('utf-8')
            _ClientHandler.log_info("Client-ID:{0}; register(); got devicetype:{1}".format(self._myownID,self._client_devicetype))
            #send client-ID to client
            sendtemp=str(self._myownID)
            self.request.sendall(sendtemp.encode("utf-8"))
        except socket.timeout:
            _ClientHandler.log_critical("Client-ID:{0}; Timeout occured, no devicetype was send".format(self._myownID))
            raise
        except socket.error as e:
            # Something else happened, handle error, exit, etc.
            _ClientHandler.log_critical("Client-ID:{0}; error '{1}' on socket.recv or socket.send".format(self._myownID, e))
            raise
        except Exception as e:
            _ClientHandler.log_critical("Client-ID:{0}; unkown error '{1}'".format(self._myownID,e))
            raise
        finally:
            self.request.settimeout(None) 
Example #3
Source File: ht_proxy_if.py    From hometop_HT3 with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        _ClientHandler.log_info("csocketsendThread(); socket.send thread start")
        self._tx=None
        while self.__threadrun==True:
            try:
                # get queue-value in blocking mode
                self._tx=self._queue.get(True)
                self._queue.task_done()
            except:
                self.__threadrun=False
                _ClientHandler.log_critical("csocketsendThread();Error on queue.get()")
                raise

            try:
                self._request.sendall(bytes(self._tx))
            except:
                self.__threadrun=False
                _ClientHandler.log_critical("csocketsendThread();Error on socket.send")
                raise

        _ClientHandler.log_info("csocketsendThread(); socket.send thread terminated") 
Example #4
Source File: qemu_virtio_port.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, port, data, exit_event, quiet=False):
        """
        :param port: Destination port.
        :param data: The data intend to be send in a loop.
        :param exit_event: Exit event.
        :param quiet: If true don't raise event when crash.
        """
        Thread.__init__(self)
        self.port = port
        # FIXME: socket.send(data>>127998) without read blocks thread
        if len(data) > 102400:
            data = data[0:102400]
            logging.error("Data is too long, using only first %d bytes",
                          len(data))
        self.data = data
        self.exitevent = exit_event
        self.idx = 0
        self.quiet = quiet
        self.ret_code = 1    # sets to 0 when finish properly 
Example #5
Source File: tcp.py    From moler with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send(self, data):
        """
        Send data via TCP service.

        :param data: data
        :type data: str
        """
        try:
            self.socket.send(data)
            # TODO: rework logging to have LogRecord with extra=direction
            # TODO: separate data sent/received from other log records ?
            self._debug('> {}'.format(data))
        except socket.error as serr:
            if (serr.errno == 10054) or (serr.errno == 10053):
                self._close_ignoring_exceptions()
                info = "{} during send msg '{}'".format(serr.errno, data)
                raise RemoteEndpointDisconnected('Socket error: ' + info)
            else:
                raise 
Example #6
Source File: qemu_virtio_port.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, port, exit_event, queues, blocklen=1024,
                 migrate_event=None, reduced_set=False):
        """
        :param port: Destination port
        :param exit_event: Exit event
        :param queues: Queues for the control data (FIFOs)
        :param blocklen: Block length
        :param migrate_event: Event indicating port was changed and is ready.
        """
        Thread.__init__(self)
        self.port = port
        self.port.sock.settimeout(1)
        self.queues = queues
        # FIXME: socket.send(data>>127998) without read blocks thread
        if blocklen > 102400:
            blocklen = 102400
            logging.error("Data is too long, using blocklen = %d",
                          blocklen)
        self.blocklen = blocklen
        self.exitevent = exit_event
        self.migrate_event = migrate_event
        self.idx = 0
        self.ret_code = 1    # sets to 0 when finish properly
        self.reduced_set = reduced_set 
Example #7
Source File: iostream.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def write_to_fd(self, data: memoryview) -> int:
        try:
            return self.socket.send(data)  # type: ignore
        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
        finally:
            # Avoid keeping to data, which can be a memoryview.
            # See https://github.com/tornadoweb/tornado/pull/2008
            del data 
Example #8
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def testSend(self):
        self.serv.send(MSG) 
Example #9
Source File: test_socket.py    From BinderFilter with MIT License 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 #10
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testRecvIntoArray(self):
        with test_support.check_py3k_warnings():
            buf = buffer(MSG)
        self.serv_conn.send(buf) 
Example #11
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testRecvFromIntoArray(self):
        with test_support.check_py3k_warnings():
            buf = buffer(MSG)
        self.serv_conn.send(buf) 
Example #12
Source File: test_socket.py    From oss-ftp with MIT License 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 #13
Source File: test_socket.py    From oss-ftp with MIT License 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
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def _testRecv(self):
        self.cli.send(MSG) 
Example #15
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testRecv(self):
        self.cli.send(MSG) 
Example #16
Source File: test_socket.py    From oss-ftp with MIT License 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
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def _testRecvFromIntoArray(self):
        with test_support.check_py3k_warnings():
            buf = buffer(MSG)
        self.serv_conn.send(buf) 
Example #18
Source File: test_jyserver.py    From PyDev.Debugger with Eclipse Public License 1.0 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 #19
Source File: test_socket.py    From oss-ftp with MIT License 5 votes vote down vote up
def _testRecvFromIntoSmallBuffer(self):
        with test_support.check_py3k_warnings():
            buf = buffer(MSG)
        self.serv_conn.send(buf) 
Example #20
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testRecv(self):
        self.cli.connect((HOST, self.port))
        time.sleep(0.1)
        self.cli.send(MSG) 
Example #21
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def testSend(self):
        self.serv.send(MSG) 
Example #22
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testStream(self):
        self.cli.send(MSG)
        self.cli.close() 
Example #23
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testShutdown(self):
        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 #24
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testDup(self):
        self.serv_conn.send(MSG) 
Example #25
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testOverFlowRecvFrom(self):
        self.serv_conn.send(MSG) 
Example #26
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testRecvFrom(self):
        self.serv_conn.send(MSG) 
Example #27
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testOverFlowRecv(self):
        self.serv_conn.send(MSG) 
Example #28
Source File: test_socket.py    From BinderFilter with MIT License 5 votes vote down vote up
def _testRecv(self):
        self.serv_conn.send(MSG) 
Example #29
Source File: test_socket.py    From BinderFilter with MIT License 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 #30
Source File: mtprotoproxy.py    From mtprotoproxy with MIT License 5 votes vote down vote up
def setup_asyncio():
    # get rid of annoying "socket.send() raised exception" log messages
    asyncio.constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES = 100