title: When opening my web server the browser says ERR_INVALID_HTTP_RESPONSE
body: <p>I tried to make a web server on port 4460 but when i type &quot;http://127.0.0.1:4460/&quot; in the browser
  address bar the browser says ERR_INVALID_HTTP_RESONSE.(Google Chrome).Browser is latest version.
  <br>
  <strong>The code did not raise any errors and did not send any bad_gateway requests.it did not access the .ico file.</strong>
  <br>
  Python ver:3.8.10
  <br>
  my code:</p>
  <pre class="lang-py prettyprint-override"><code>import socket
  from socket import AF_INET,SOCK_STREAM
  from threading import Lock
  from pprint import pprint
  from threadtools import threaded
  from email.utils import format_datetime as fmd
  import datetime
  from deflate import gzip_compress
  ms = (lambda x:x/1000)
  socket.setdefaulttimeout(ms(700))
  ol = Lock()
  plok = Lock()
  ENCODINGS = &quot;utf-8 utf-16 cp936 latin-1&quot;.split()
  response_header = b&quot;&quot;&quot;\
  200 OK
  Content-Type: text/html
  Content-Length: $$CTXLN$$
  Content-Encoding: gzip
  Connection: close
  Date: $$DATE$$
  Keep-Alive: timeout=2, max=2
  $$CTX$$&quot;&quot;&quot;
  bad_gateway = b&quot;&quot;&quot;\
  502 Bad Gateway
  Content-type:text/html
  Content-legth:0&quot;&quot;&quot;
  def decode(x,verbose=False):
      for enc in ENCODINGS:
          flag = False
          try:
              return x.decode(enc)
          except:
              flag = True
          finally:
              print(&quot;Decoded in:&quot;+enc) if(not flag)and verbose else None
      return &quot;&quot;
  def startswithany(a,lis):
      for x in lis:
          if a.startswith(x):
              return True
      return False
  def is_newline(x):
      return x in (&quot;\r\n&quot;,&quot;\n&quot;)
  def load_rsrc(acpt):
      if &quot;text/html&quot; in acpt or &quot;text/*&quot; in acpt or &quot;*/*&quot; in acpt:
          return open(&quot;response.html&quot;,&quot;rb&quot;).read()
      elif &quot;image/ico&quot; in acpt or &quot;image/*&quot; in acpt:
          return open(&quot;response.ico&quot;,&quot;rb&quot;).read()
      else:
          return b&quot;&quot;
  def handle_connection(cnct,addr):
      global pending
      with plok:
          pending += 1
      try:
          if pending &gt; 20:#Too many connections!!!
              cnct.send(bad_gateway)
          with ol:
              print(f&quot;----------------\nConnection from:{addr}\n&quot;)
          has_ln = True
          data = b&quot;&quot;
          ctx = &quot;&quot;
          headers = {&quot;Unknown-Lines&quot;:[]}
          while True:
              data = b&quot;&quot;
              while not decode(data).endswith(&quot;\n&quot;):#\r\n ends with \n
                  try:
                      data += cnct.recv(1)
                  except:#timeout
                      has_ln = False
                      break
              if not has_ln:
                  break
              assert len(data)
              data = decode(data).strip(&quot; &quot;)
              assert not data.startswith(&quot; &quot;)
              if is_newline(data):#empty line
                  continue
              if startswithany(data,(&quot;GET&quot;,&quot;POST&quot;,&quot;PUT&quot;)):
                  headers[&quot;Request-Type&quot;] = data.strip()
              else:
                  dsp = data.split(&quot;:&quot;,1)
                  if len(dsp)!=2:
                      print(f&quot;Unknown header:{data}&quot;)
                      headers[&quot;Unknown-Lines&quot;].append(data)
                  else:
                      a,b = data.split(&quot;:&quot;,1)
                      b = b.strip()
                      headers[a] = b
          with ol:
              print(f&quot;Headers:&quot;)
              for k,v in headers.items():
                  print(f&quot;{k}:{v}&quot;)
          accept = headers.get(&quot;Accept&quot;,&quot;text/html&quot;)
          accept = accept.split(&quot;,&quot;)
          q = []
          for i,x in enumerate(accept):
              if &quot;;q=&quot; in x:
                  a,b = x.split(&quot;;q=&quot;)
                  b = float(b)
                  accept[i] = a
                  q.append(b)
          rt = tuple(map(str.strip,headers.get(&quot;Request-Type&quot;,&quot;GET/HTTP/1.0&quot;).split(&quot;/&quot;)))
          req = rt[0]#GET/POST/PUT
          protocol = rt[1]#HTTP;NO SECURE SERVER FOR NOW
          ver = rt[2]#version
          assert ver in (&quot;1.0&quot;,&quot;1.1&quot;)
          now = datetime.datetime.now(datetime.timezone.utc)
          datestr = fmd(now,True).encode()
          ctx = load_rsrc(accept)
          ln = str(len(ctx)+1).encode()
          response = response_header.replace(b&quot;$$CTXLN$$&quot;,ln)\
                                    .replace(b&quot;$$CTX$$&quot;,ctx)\
                                    .replace(b&quot;$$DATE$$&quot;,datestr)
          response_cmpr = gzip_compress(response)
          cnct.send(response_cmpr)
          print(&quot;Sent:&quot;)
          print(response.decode())
          if headers.get(&quot;Connection&quot;,&quot;Keep-alive&quot;) == &quot;Keep-alive&quot;:
              import time
              time.sleep(2)
      finally:
          cnct.close()
          with plok:
              pending -= 1
  skt = socket.socket(AF_INET,SOCK_STREAM)
  skt.bind((&quot;&quot;,4460))
  skt.listen(3)
  skt.settimeout(None)
  pending = 0
  while True:
      cn,ad = skt.accept()
      handle_connection(cn,ad)
  </code></pre>