Solved

Sockets recv function on a new line

Posted on 2006-11-10
2
2,246 Views
Last Modified: 2010-04-16
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..
0
Comment
Question by:Tabris42
2 Comments
 
LVL 14

Accepted Solution

by:
RichieHindle earned 500 total points
ID: 17914999
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(('127.0.0.1', 1234))
    listener.listen(5)
    while 1:
        client, _ = listener.accept()
        worker_thread = threading.Thread(target=worker, args=(client,))
        worker_thread.setDaemon(True)
        worker_thread.start()

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

if __name__ == '__main__':
    run()
0
 

Author Comment

by:Tabris42
ID: 17915164
That's very helpful, thanks!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

A set of related code is known to be a Module, it helps us to organize our code logically which is much easier for us to understand and use it. Module is an object with arbitrarily named attributes which can be used in binding and referencing. …
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now