Take the 2-minute tour ×

I coded a server program using python.

I'm trying to get a string but i got only a character! How can I receive a string?

def handleclient(connection):                                           
    while True:                             
        rec = connection.recv(200)
        if rec == "help": #when I put help in the client program, rec = 'h' and not to "help"
            connection.send("Help Menu!")


def main():
   while True:
        connection, addr = sckobj.accept()   
        connection.send("Message: ")   
        IpClient = addr[0]
        print 'Server was connected by :',IpClient

        thread.start_new(handleclient, (connection,))   
share|improve this question
Are you using non-blocking sockets? –  cdarke Nov 5 '12 at 10:20
add comment

1 Answer

up vote 2 down vote accepted

With TCP/IP connections your message can be fragmented. It might send one letter at a time, or it might send the whole lot at once - you can never be sure.

Your programs needs to be able to handle this fragmentation. Either use a fixed length packet (so you always read X bytes) or send the length of the data at the start of each packet. If you are only sending ASCII letters, you can also use a specific character (eg \n) to mark the end of transmission. In this case you would read until the message contains a \n.

recv(200) isn't guaranteed to receive 200 bytes - 200 is just the maximum.

This is an example of how your server could look:

rec = ""
while True:
    rec += connection.recv(1024)
    rec_end = rec.find('\n')
    if rec_end != -1:
        data = rec[:rec_end]

        # Do whatever you want with data here

        rec = rec[rec_end+1:]
share|improve this answer
so I need to make a loop that will check if the data I recieve equal to \n then check check for "help". –  programmer Nov 5 '12 at 10:42
As I said, you can do it a few ways. If your message will never contain \n you can use it as a terminator. Send it at the end of your message in the client, and in the server read data until you see \n. I added some quick sample code to my answer. –  Tim Nov 5 '12 at 10:49
add comment

Your Answer


