Receive data from socket stream

Nick Craig-Wood nick at craig-wood.com
Tue Apr 29 05:30:03 EDT 2008


s0suk3 at gmail.com <s0suk3 at gmail.com> wrote:
>  But as I said in my first post, it's simple when you know the amount
>  of data that you're going to receive, or when you'll receive data
>  until the remote peer closes the connection. But what about receiving
>  a message with undetermined length in a connection that you don't want
>  to close?

You obviously need some sort of protocol.  Here is some code (taken
from a real project and modified a bit) which returns \r\n seperated
lines from a socket as they arrive which is a very simple (but
widespread) protocol.

    self.rx_buf is set to "" in the initialisation
    self.sock is the socket

    def rx_line(self):
        message = None
        while 1:
            pos = self.rx_buf.find("\r\n")
            if pos >= 0:
                message = self.rx_buf[:pos]
                self.rx_buf = self.rx_buf[pos+2:]
                break
            try:
                rx = self.sock.recv(4096)
            except socket.error, e:
                self.sock = None
                raise ServerNetworkException(e)
            if len(rx) == 0:
                self.sock = None
                raise ServerDisconnectedException()
            self.rx_buf += rx
	return message

Sorry I mis-understood your original post!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list