0

My client sends a message to server. The server collects the message 16 bytes each time and when it receives anything less than 16 bytes, it returns the message (after concatenation) back to the client.

Here is the code from server.py:

    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM,socket.IPPROTO_IP)
    sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

    sock.bind(address)
    sock.listen(1)

    try:
        while True:
            conn,add=sock.accept()
            addr=(conn,add)
            print add
            try:
                data = ''
                while True:

                    recvdata=conn.recv(16)
                    print recvdata
                    data+=recvdata
                    if len(recvdata)<16:
                        print >>log_buffer,"sending data"
                        conn.sendall(data)
                        break


            finally:
                conn.close()


    except KeyboardInterrupt:
        sock.close()

The code works well for messages above 16 and less than 16 byte length, when it is exactly 16 or mutliples of 16, it is not sending back to client. how do I fix for this? `

0

1 Answer 1

1

you don't say anything about what it should do at exactly a multiple of 16.
The code you posted will not send it back though.
Change < to <=.

< means less than.

<= means less than or equal to (multiple of).

Code:

if len(recvdata)<=16:
    print >>log_buffer,"sending data"
    conn.sendall(data)
    break

Edit:

If you are just getting the message and returning whole bytes you can do the following:

while True:
    conn,add=sock.accept()
    addr=(conn,add)
    print add
    try:
        recvdata=conn.recv(2048) #however much you need

        wholebytes = len(recvdata) / 16 # get the number of whole bytes

        # loop to send messages of length 16 with whole bytes
        for i in range(wholebytes):
            data = recvdata[i*16:(i+1)*16]
            print >>log_buffer,"sending data"
            conn.sendall(data)

        break
11
  • I do not want to send all the message is collected. what if I have 32 bytes, I will send two messages back. Jan 9, 2014 at 23:40
  • if you have 32 bytes you will send 2 messages since you only receive 16 bytes at a time.
    – Serdalis
    Jan 9, 2014 at 23:41
  • but I am breaking of the loop, if I have 32 bytes, I will send first 16 bytes, but I am breaking immediately before I collect the remaining 16 and send it back Jan 9, 2014 at 23:44
  • don't break then. or only break on < 16 bytes.
    – Serdalis
    Jan 9, 2014 at 23:46
  • its slightly complicated than it is. what if the last bytes I get is exactly 16 length, it neither breaks or sends back the message. (the exact question above) Jan 9, 2014 at 23:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.