Python socket.recv() Examples

The following are 30 code examples for showing how to use socket.recv(). 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: movistartv2xmltv   Author: ese   File: tva.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _getchunk(self,socket):
        #Struct of header - first 12 bytes
        # end   xmlsize   type   ?  id        chunk# *10   total chunks     \0
        # --   --------   -----  ------  ----  ---------  -------------      --
        # 00   00 00 00    F1    X 0 00   00     00 00          00           00
        #FIXME: XMLsize print is incorrect
        data = socket.recv(1500)
        chunk = {}
        chunk["end"] = struct.unpack('B',data[:1])[0]
        chunk["size"] = struct.unpack('>HB',data[1:4])[0]
        chunk["filetype"] = struct.unpack('B',data[4:5])[0]
        chunk["fileid"] = struct.unpack('>H',data[5:7])[0]&0x0fff
        chunk["chunk_number"] = struct.unpack('>H',data[8:10])[0]/0x10
        chunk["chunk_total"] = struct.unpack('B',data[10:11])[0]
        chunk["data"] = data[12:]
        self.logger.debug("Chunk "+str(chunk["chunk_number"])+"/"+str(chunk["chunk_total"])+" ---- e:"+str(chunk["end"])+" s:"+        str(chunk["size"])+" f:"+str(chunk["fileid"]))
        return chunk 
Example 2
Project: vscode-esp-idf-extension   Author: espressif   File: client_da.py    License: Apache License 2.0 6 votes vote down vote up
def _read_from_socket(self):
        """
        Read socket.recv to the readed_jsons queue

        Returns
        -------

        """
        data = ""
        try:
            data = self.__socket.recv(SOCKET_BUFFER_SIZE)
        except socket.timeout:
            self.state["Errors"] = True
            raise socket.timeout("Error! Socket did not get info, when expected")
        if not data:
            s = "Empty"
        else:
            s = data.decode('utf-8')
        print("\n === Read from socket === \n%s\n" % s)
        self._load_to_queue(s) 
Example 3
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 6 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(socket.error):
            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 4
Project: avocado-vt   Author: avocado-framework   File: qemu_monitor.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _recvall(self):
        """
        Receive btyes from socket.recv().

        return s type: bytes
        """
        s = b""
        while self._data_available():
            try:
                data = self._socket.recv(1024)
            except socket.error as e:
                raise MonitorSocketError("Could not receive data from monitor",
                                         e)
            if not data:
                self._server_closed = True
                break
            s += data
        return s 
Example 5
Project: vnpy_crypto   Author: birforce   File: pool.py    License: MIT License 6 votes vote down vote up
def _raise_connection_failure(self, error):
        # Catch *all* exceptions from socket methods and close the socket. In
        # regular Python, socket operations only raise socket.error, even if
        # the underlying cause was a Ctrl-C: a signal raised during socket.recv
        # is expressed as an EINTR error from poll. See internal_select_ex() in
        # socketmodule.c. All error codes from poll become socket.error at
        # first. Eventually in PyEval_EvalFrameEx the interpreter checks for
        # signals and throws KeyboardInterrupt into the current frame on the
        # main thread.
        #
        # But in Gevent and Eventlet, the polling mechanism (epoll, kqueue,
        # ...) is called in Python code, which experiences the signal as a
        # KeyboardInterrupt from the start, rather than as an initial
        # socket.error, so we catch that, close the socket, and reraise it.
        self.close()
        if isinstance(error, socket.error):
            _raise_connection_failure(self.address, error)
        else:
            raise error 
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: hometop_HT3   Author: norberts1   File: ht_proxy_if.py    License: GNU General Public License v3.0 6 votes vote down vote up
def read(self, size=1):
        """Read size bytes from the connected socket. It will block
           until the requested number of bytes are read.
        """
        if self._socket==None:
            raise ("Client-ID:{0}; cht_socket_client.read(); error:socket not initialised".format(self._clientID))
        read=bytearray()
        while len(read) < size:
            try:
                buffer=self._socket.recv(size)
            except:
                self._socket.close()
                self.log_critical("Client-ID:{0}; cht_socket_client.read(); error on socket.recv".format(self._clientID))
                raise

            if not buffer:
                self._socket.close()
                self.log_critical("Client-ID:{0}; cht_socket_client.read(); peer closed socket".format(self._clientID))
                raise
            else:
                read.extend(buffer)

        return bytes(read) 
Example 8
Project: BinderFilter   Author: dxwu   File: test_socket.py    License: MIT License 6 votes vote down vote up
def testRecv(self):
        # Testing non-blocking recv
        conn, addr = self.serv.accept()
        conn.setblocking(0)
        try:
            msg = conn.recv(len(MSG))
        except socket.error:
            pass
        else:
            self.fail("Error trying to do non-blocking recv.")
        read, write, err = select.select([conn], [], [])
        if conn in read:
            msg = conn.recv(len(MSG))
            conn.close()
            self.assertEqual(msg, MSG)
        else:
            self.fail("Error during select call to non-blocking socket.") 
Example 9
Project: oss-ftp   Author: aliyun   File: test_socket.py    License: MIT License 6 votes vote down vote up
def testRecv(self):
        # Testing non-blocking recv
        conn, addr = self.serv.accept()
        conn.setblocking(0)
        try:
            msg = conn.recv(len(MSG))
        except socket.error:
            pass
        else:
            self.fail("Error trying to do non-blocking recv.")
        read, write, err = select.select([conn], [], [])
        if conn in read:
            msg = conn.recv(len(MSG))
            conn.close()
            self.assertEqual(msg, MSG)
        else:
            self.fail("Error during select call to non-blocking socket.") 
Example 10
Project: satori   Author: leancloud   File: pool.py    License: Apache License 2.0 6 votes vote down vote up
def _raise_connection_failure(self, error):
        # Catch *all* exceptions from socket methods and close the socket. In
        # regular Python, socket operations only raise socket.error, even if
        # the underlying cause was a Ctrl-C: a signal raised during socket.recv
        # is expressed as an EINTR error from poll. See internal_select_ex() in
        # socketmodule.c. All error codes from poll become socket.error at
        # first. Eventually in PyEval_EvalFrameEx the interpreter checks for
        # signals and throws KeyboardInterrupt into the current frame on the
        # main thread.
        #
        # But in Gevent and Eventlet, the polling mechanism (epoll, kqueue,
        # ...) is called in Python code, which experiences the signal as a
        # KeyboardInterrupt from the start, rather than as an initial
        # socket.error, so we catch that, close the socket, and reraise it.
        self.close()
        if isinstance(error, socket.error):
            _raise_connection_failure(self.address, error)
        else:
            raise error 
Example 11
Project: airflow   Author: apache   File: test_ssh.py    License: Apache License 2.0 6 votes vote down vote up
def test_tunnel(self):
        hook = SSHHook(ssh_conn_id='ssh_default')

        import subprocess
        import socket

        subprocess_kwargs = dict(
            args=["python", "-c", HELLO_SERVER_CMD],
            stdout=subprocess.PIPE,
        )
        with subprocess.Popen(**subprocess_kwargs) as server_handle, hook.create_tunnel(2135, 2134):
            server_output = server_handle.stdout.read(5)
            self.assertEqual(b"ready", server_output)
            socket = socket.socket()
            socket.connect(("localhost", 2135))
            response = socket.recv(5)
            self.assertEqual(response, b"hello")
            socket.close()
            server_handle.communicate()
            self.assertEqual(server_handle.returncode, 0) 
Example 12
Project: RSB-Framework   Author: tarcisio-marinho   File: backdoor.py    License: GNU General Public License v3.0 6 votes vote down vote up
def download(s):
    filename = s.recv(1024)
    print(filename)
    if(os.path.isfile(filename)):
        with open(filename, 'rb') as f: 
            l = f.read(1024)
            l = 'True+/-' + l
            while(l):
                s.send(l)
                l = f.read(1024)

        print('sent')
        s.shutdown(s.SHUT_WR)

    else:
        s.send('False') 
Example 13
Project: testplan   Author: Morgan-Stanley   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def receive(self, size, timeout=30):
        """
        Receive a message.

        :param size: Number of bytes to receive.
        :type size: ``int``
        :param timeout: Timeout in seconds.
        :type timeout: ``int``
        :return: message received
        :rtype: ``bytes``
        """
        if timeout != self._timeout:
            self._timeout = timeout
        self._client.settimeout(timeout)
        try:
            msg = self._client.recv(size)
        except Exception:
            if timeout == 0:
                raise socket.timeout
            raise
        return msg 
Example 14
Project: serfclient-py   Author: KushalP   File: test_connection.py    License: MIT License 6 votes vote down vote up
def test_connection_closed(self, rpc):
        rpc.handshake()

        # Mock socket.recv returning an empty string, as it does when the
        # connection has been closed.
        class MockSocket:
            def sendall(self, content):
                pass

            def recv(self, size):
                return ""

            def close(self):
                pass

        rpc._socket = MockSocket()

        with pytest.raises(connection.SerfConnectionError):
            rpc.handshake() 
Example 15
Project: prometheus-nagios-exporter   Author: m-lab   File: nagios_exporter.py    License: Apache License 2.0 6 votes vote down vote up
def _receive(self, count):
        """Reads data from the livestatus plugin."""
        results = []
        while count > 0:
            try:
                data = self._sock.recv(count)
            except socket.error as err:
                raise NagiosResponseError(err)
            if len(data) == 0:
                msg = 'Failed to read data from nagios server.'
                raise NagiosResponseError(msg)
            count -= len(data)

            # socket.recv() returns str in Python 2 and bytes in Python 3
            if sys.version_info[0] >= 3:
                data = data.decode()

            results.append(data)
        return ''.join(results) 
Example 16
Project: networking   Author: RussianOtter   File: DH.py    License: GNU General Public License v3.0 6 votes vote down vote up
def initDiffieHellman(self):
		if self.request.recv(1024).decode() != "connected":
			print("Error while connecting")
		publicSecret = self.__dh.calcPublicSecret()
		step1 = "{"
		step1 += "\"dh-keyexchange\":"
		step1 += "{"
		step1 += "\"step\": {},".format(1)
		step1 += "\"base\": {},".format(self.__dh.base)
		step1 += "\"prime\": {},".format(self.__dh.sharedPrime)
		step1 += "\"publicSecret\": {}".format(publicSecret)
		step1 += "}}"
		self.request.send(step1.encode())
		step2 = self.request.recv(1024)
		if self.__debugflag:
			print(step2)
		jsonData = json.loads(step2.decode())
		jsonData = jsonData["dh-keyexchange"]
		publicSecret = int(jsonData["publicSecret"])
		self.__dh.calcSharedSecret(publicSecret) 
Example 17
Project: networking   Author: RussianOtter   File: DH.py    License: GNU General Public License v3.0 6 votes vote down vote up
def initDiffieHellman(self, socket):
		socket.send("connected".encode())
		step1 = socket.recv(5000)
		if self.__debugflag:
			print(step1)
		jsonData = json.loads(step1.decode())
		jsonData = jsonData["dh-keyexchange"]
		self.__dh.base = int(jsonData["base"])
		self.__dh.sharedPrime = int(jsonData["prime"])
		publicSecret = int(jsonData["publicSecret"])
		calcedPubSecret = str(self.__dh.calcPublicSecret())
		step2 = "{"
		step2 += "\"dh-keyexchange\":"
		step2 += "{"
		step2 += "\"step\": {},".format(2)
		step2 += "\"publicSecret\": {}".format(calcedPubSecret)
		step2 += "}}"
		socket.send(step2.encode())
		self.__dh.calcSharedSecret(publicSecret) 
Example 18
Project: moler   Author: nokia   File: tcp.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def receive(self, timeout=30):
        """
        Receive data.

        :param timeout: time-out, default 30 sec
        :type timeout: float
        """
        if not self.socket:
            raise RemoteEndpointNotConnected()
        ready = select.select([self.socket], [], [], timeout)
        if ready[0]:
            try:
                data = self.socket.recv(self.receive_buffer_size)
                # 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()
                    raise RemoteEndpointDisconnected(serr.errno)
                else:
                    raise serr

            if not data:
                self._close_ignoring_exceptions()
                raise RemoteEndpointDisconnected()
            return data

        else:
            # don't want to show class name - just tcp address
            # want same output from any implementation of TCP-connection
            info = "Timeout (> %.3f sec) on {}".format(timeout, self)
            raise ConnectionTimeout(info) 
Example 19
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testRecv(self):
        # Testing large receive over TCP
        msg = self.cli_conn.recv(1024)
        self.assertEqual(msg, MSG) 
Example 20
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testOverFlowRecv(self):
        # Testing receive in chunks over TCP
        seg1 = self.cli_conn.recv(len(MSG) - 3)
        seg2 = self.cli_conn.recv(1024)
        msg = seg1 + seg2
        self.assertEqual(msg, MSG) 
Example 21
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testSendAll(self):
        # Testing sendall() with a 2048 byte string over TCP
        msg = ''
        while 1:
            read = self.cli_conn.recv(1024)
            if not read:
                break
            msg += read
        self.assertEqual(msg, 'f' * 2048) 
Example 22
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testFromFd(self):
        # Testing fromfd()
        fd = self.cli_conn.fileno()
        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        msg = sock.recv(1024)
        self.assertEqual(msg, MSG) 
Example 23
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testDup(self):
        # Testing dup()
        sock = self.cli_conn.dup()
        self.addCleanup(sock.close)
        msg = sock.recv(1024)
        self.assertEqual(msg, MSG) 
Example 24
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testSendtoAndRecv(self):
        # Testing sendto() and Recv() over UDP
        msg = self.serv.recv(len(MSG))
        self.assertEqual(msg, MSG) 
Example 25
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testClose(self):
        conn, addr = self.serv.accept()
        conn.close()

        sd = self.cli
        read, write, err = select.select([sd], [], [], 1.0)
        self.assertEqual(read, [sd])
        self.assertEqual(sd.recv(1), '') 
Example 26
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testRecv(self):
        msg = self.serv.recv(1024)
        self.assertEqual(msg, MSG) 
Example 27
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testSend(self):
        msg = self.cli.recv(1024)
        self.assertEqual(msg, MSG) 
Example 28
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, recv_funcs=()):
            # A generator that returns callables that we'll call for each
            # call to recv().
            self._recv_step = iter(recv_funcs) 
Example 29
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def recv(self, size):
            return self._recv_step.next()() 
Example 30
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testInsideTimeout(self):
        self.cli = sock = socket.create_connection((HOST, self.port))
        data = sock.recv(5)
        self.assertEqual(data, "done!")