Search code examples
pythonsocketshttpheaderrecv

Python can't receive user data in HTTP socket server


I can't get the data in recv() I want the data that the user inputs in form fields

Code:

def recvall(self, conn):
    BUFF_SIZE = 4096 # 4 KiB
    data = ""

    while True:

        packet = conn.recv(BUFF_SIZE).decode('utf-8')
        data += packet

        if len(packet) < BUFF_SIZE:
            break

    print (data)

output:

POST /search HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 14
Cache-Control: max-age=0
Origin: http://localhost
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://localhost/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

It seems to be missing a line or something i've tried everything i want the data at the end


Solution

  • You have stopped reading after the header sequence as Steffen correctly observed. The following code should work (beware, untested!):

    def recvall(self, conn):
        BUFF_SIZE = 4096
    
        while True:
            packet = conn.recv(BUFF_SIZE)
            if not packet:
                break
            print packet.decode('utf-8')