• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3926
  • Last Modified:

Sockets recv function on a new line

Hi experts,

I'm writing a program that receives data from a server and prints it.. but I would like to do this line by line. That is, everytime the server sends me a line, I want the line printed. I'm not sure on how to do this though, the current method is "data = fsocket.recv(1024)", however my assumption is that only reads in 1024 bytes at a time. Is it possible to have it receive one line and not wait till the 1024 bytes are filled? Thanks..
1 Solution
recv(1024) will read *up to* 1024 bytes, blocking if there's nothing ready to read.  It won't wait for 1024 bytes - it will wait for *some* bytes.  You need to read those bytes then look for newlines youself.  (If recv returns an empty string, that means the socket has been closed by the other end.)

Here's an example script, which reads data until it has a line, then both prints that line and echoes it back to the client.

import socket, threading

def run():
    listener = socket.socket()
    listener.bind(('', 1234))
    while 1:
        client, _ = listener.accept()
        worker_thread = threading.Thread(target=worker, args=(client,))

def worker(client):
    data = ""
    while 1:
        packet = client.recv(1024)
        if not packet:
            # The socket has been closed.
        data += packet
        if chr(4) in data or chr(26) in data:
            # User has hit Ctrl+D or Ctrl+Z
        if '\n' in data:
            line, data = data.split('\n', 1)
            print line

if __name__ == '__main__':
Tabris42Author Commented:
That's very helpful, thanks!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now