Question

I'm getting started with Socket programming in Python. As part of my requirement I want to send some requests (call send_post_requests) and then receive all of them.

Can anyone tell me what I'm doing wrong here. Right now I'm able to receive only first response.

Here's my code snippet-

def send_post_request(s,i="1",question='{"a": {"b":"dummy}}'):   

        s.send('POST /request HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: identity\r\nContent-Length: '+str(len(question))+'\r\nrequest-id: '+i+'\r\nConnection: Keep-Alive\r\nContent-Type: application/json\r\n\r\n')

        s.send(question)


def pipe(noOfSockets=1,noOfRequest = 5,question='{"a": {"b":"dummy}}',sizeFactor = 1):
        sockets =[]
        for i in range(0,noOfSockets ):
            sockets.append(socket( AF_INET, SOCK_STREAM))

        for s in sockets:
            try:
                s.connect( (<IP>, <port>))
                for i in range(0,noOfRequest):   
                    send_post_request(s,str(i),question)

            except(error,timeout), e:
                print(e)
            except Exception, e:
                print("unknown except(%s) :(" % e)

        passes =0
        allResp =[]
        for s in sockets:
            sleep(2)
            size = noOfRequest * 1000 *sizeFactor
            responses = s.recv(size)

            allResp.append(responses) 

        return allResp 
Was it helpful?

Solution

Webservers normally close the connection after one request. Use a library for http-requests like urllib2 or requests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top