Python socket.send() Examples

The following are 30 code examples for showing how to use socket.send(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: moler   Author: nokia   File: tcp.py    License: 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 2
Project: avocado-vt   Author: avocado-framework   File: qemu_virtio_port.py    License: 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 3
Project: avocado-vt   Author: avocado-framework   File: qemu_virtio_port.py    License: 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 4
Project: opendevops   Author: opendevops-cn   File: iostream.py    License: 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 5
Project: hometop_HT3   Author: norberts1   File: ht_proxy_if.py    License: 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 6
Project: hometop_HT3   Author: norberts1   File: ht_proxy_if.py    License: 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 7
Project: mtprotoproxy   Author: alexbers   File: mtprotoproxy.py    License: 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 8
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: MIT License 5 votes vote down vote up
def write_to_fd(self, data):
        return self.socket.send(data) 
Example 9
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: 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 10
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: MIT License 5 votes vote down vote up
def write_to_fd(self, data):
        return self.socket.send(data) 
Example 11
Project: tornado-zh   Author: tao12345666333   File: iostream.py    License: 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 12
Project: moler   Author: nokia   File: tcp.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, moler_connection,
                 port, host="localhost", receive_buffer_size=64 * 4096,
                 logger=None):
        """Initialization of TCP-threaded connection."""
        super(ThreadedTcp, self).__init__(port=port, host=host,
                                          receive_buffer_size=receive_buffer_size,
                                          logger=logger)
        self.pulling_thread = None
        # make Moler happy (3 requirements) :-)
        self.moler_connection = moler_connection  # (1)
        self.moler_connection.how2send = self.send  # (2) 
Example 13
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.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 14
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testRecv(self):
        self.serv_conn.send(MSG) 
Example 15
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testOverFlowRecv(self):
        self.serv_conn.send(MSG) 
Example 16
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testRecvFrom(self):
        self.serv_conn.send(MSG) 
Example 17
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testOverFlowRecvFrom(self):
        self.serv_conn.send(MSG) 
Example 18
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testDup(self):
        self.serv_conn.send(MSG) 
Example 19
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testShutdown(self):
        self.serv_conn.send(MSG)
        self.serv_conn.shutdown(2) 
Example 20
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.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 21
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testRecv(self):
        self.cli.send(MSG) 
Example 22
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testSend(self):
        self.serv.send(MSG) 
Example 23
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.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 socket.error
        self.event.wait()

        # send data: recv() will no longer block
        self.cli.sendall(MSG) 
Example 24
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.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 25
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.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 26
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.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 27
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.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 28
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testStream(self):
        self.cli.send(MSG)
        self.cli.close() 
Example 29
Project: px   Author: genotrance   File: px.py    License: MIT License 5 votes vote down vote up
def run_pool():
    try:
        httpd = ThreadedTCPServer((State.config.get("proxy", "listen").strip(),
                                   State.config.getint("proxy", "port")), Proxy)
    except OSError as exc:
        if "attempt was made" in str(exc):
            print("Px failed to start - port in use")
        else:
            pprint(exc)
        return

    mainsock = httpd.socket

    print_banner()

    if hasattr(socket, "fromshare"):
        workers = State.config.getint("settings", "workers")
        for i in range(workers-1):
            (pipeout, pipein) = multiprocessing.Pipe()
            p = multiprocessing.Process(target=start_worker, args=(pipeout,))
            p.daemon = True
            p.start()
            while p.pid is None:
                time.sleep(1)
            pipein.send(mainsock.share(p.pid))

    serve_forever(httpd)

###
# Proxy detection 
Example 30
Project: avocado-vt   Author: avocado-framework   File: qemu_virtio_port.py    License: GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        logging.debug("ThSend %s: run", self.getName())
        try:
            while not self.exitevent.isSet():
                self.idx += self.port.send(self.data)
            logging.debug("ThSend %s: exit(%d)", self.getName(),
                          self.idx)
        except Exception as ints:
            if not self.quiet:
                raise ints
            logging.debug(ints)
        self.ret_code = 0