Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6051057
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T07:45:34+00:00 2026-05-23T07:45:34+00:00

I’ve written a miniature proxy module in Python 3 to simply sit between my

  • 0

I’ve written a miniature proxy module in Python 3 to simply sit between my browser and the web. My goal is to merely proxy the traffic going back and forth. One behavior of the program is to save the website responses I get in a local directory.

Everything works the way I expect, except for the simple fact that using socket.recv() in a loop seems to never yield the blank bytes object implied in the examples provided in the docs. Virtually every online example talks about the blank string coming through the socket when the server closes it.

My assumption is that something is going on via the keep-alive header, where the remote server never closes the socket unless its own timeout threshold is reached. Is this correct? If so, how on earth am I to detect when a payload is finished being sent? Observing that received data is smaller than my declared chunk size does not work at all, due to the way TCP functions.

To demonstrate, the following code opens a socket at an image file on Google’s web server. I copied the actual request string from my browser’s own requests. Running the code (remember, Python 3!) shows that binary image data is received to completion, but then the code never is capable of hitting the break statement. Only when the server closes the socket (after some 3 minutes of idle time) does this code actually reach the print command at the end of the file.

How on earth does one get around this? My goal is to not modify the behavior of my browser’s requests—I don’t want to have to set the keep-alive header to false or something gaudy like that. Is the answer to use some ugly timeouts (via socket.settimeout())? Seems laughable, but I don’t know what else could be done.

Thanks in advance.

import socket

remote_host = 'www.google.com'
remote_port = 80

remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((remote_host, remote_port))
remote_socket.sendall(b'GET http://www.google.com/images/logos/ps_logo2a_cp.png HTTP/1.1\r\nHost: www.google.com\r\nCache-Control: max-age=0\r\nPragma: no-cache\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.794.0 Safari/535.1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n\r\n')

content = b''
while True:
    msg = remote_socket.recv(1024)
    if not msg:
        break
    print(msg)
    content += msg

print("DONE: %d" % len(content))
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T07:45:34+00:00Added an answer on May 23, 2026 at 7:45 am

    If you have a keep-alive connection, there will be some indication of the message length in the headers of the response. See HTTP Message. Buffer recv until you have the complete header (terminated by a blank line), determine the message body length, and read exactly that much information.

    Here’s a simple class to buffer TCP reads until a message terminator or a specific number of bytes has been read. I added it to your example:

    import socket
    import re
    
    class MessageError(Exception): pass
    
    class MessageReader(object):
        def __init__(self,sock):
            self.sock = sock
            self.buffer = b''
    
        def get_until(self,what):
            while what not in self.buffer:
                if not self._fill():
                    return b''
            offset = self.buffer.find(what) + len(what)
            data,self.buffer = self.buffer[:offset],self.buffer[offset:]
            return data
    
        def get_bytes(self,size):
            while len(self.buffer) < size:
                if not self._fill():
                    return b''
            data,self.buffer = self.buffer[:size],self.buffer[size:]
            return data
    
        def _fill(self):
            data = self.sock.recv(1024)
            if not data:
                if self.buffer:
                    raise MessageError('socket closed with incomplete message')
                return False
            self.buffer += data
            return True
    
    remote_host = 'www.google.com'
    remote_port = 80
    
    remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    remote_socket.connect((remote_host, remote_port))
    remote_socket.sendall(b'GET http://www.google.com/images/logos/ps_logo2a_cp.png HTTP/1.1\r\nHost: www.google.com\r\nCache-Control: max-age=0\r\nPragma: no-cache\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.794.0 Safari/535.1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n\r\n')
    mr = MessageReader(remote_socket)
    header = mr.get_until(b'\r\n\r\n')
    print(header.decode('ascii'))
    m = re.search(b'Content-Length: (\d+)',header)
    if m:
        length = int(m.group(1))
        data = mr.get_bytes(length)
        print(data)
    remote_socket.close()
    

    Output

    HTTP/1.1 200 OK
    Content-Type: image/png
    Last-Modified: Thu, 12 Aug 2010 00:42:08 GMT
    Date: Tue, 21 Jun 2011 05:03:35 GMT
    Expires: Tue, 21 Jun 2011 05:03:35 GMT
    Cache-Control: private, max-age=31536000
    X-Content-Type-Options: nosniff
    Server: sffe
    Content-Length: 6148
    X-XSS-Protection: 1; mode=block
    
    
    b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01l\x00\x00\x00~\x08\x03\x00\ (rest omitted)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a bunch of posts stored in text files formatted in yaml/textile (from
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to loop through a bunch of documents I have to put
I'm making a simple page using Google Maps API 3. My first. One marker

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.