The simplest HTTP server with traffic control in history

Source: Internet
Author: User

S. py

import timeimport SimpleHTTPServerimport SocketServerBYTES_PER_SECOND=160*1024class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):    def do_GET(self):        """Serve a GET request."""        f = self.send_head()        if f:            self.copyfileobj(f, self.wfile)            f.close()    def copyfileobj(self,fsrc, fdst, length=16*1024):        """copy data from file-like object fsrc to file-like object fdst"""        count = 0        t1 = time.time()        while 1:            buf = fsrc.read(length)            if not buf:                break            fdst.write(buf)            count += len(buf)            if count >= BYTES_PER_SECOND:                count = 0                delay = 1.0 - (time.time() - t1)                if delay > 0.0:                    time.sleep(delay)                t1 = time.time()                PORT = 8000Handler = MyHTTPRequestHandlerhttpd = SocketServer.TCPServer(("127.0.0.1", PORT), Handler)print "serving at port", PORThttpd.serve_forever()



Yes, that's it! A total of 30 lines of code. Bytes_per_second is used to specify the maximum number of bytes transmitted per second. 127.0.0.1 is the IP address that the server listens. 8000 is the port listened by the HTTP server.

This is why writing a python program is a pleasure. Python, known as battery include, is a popular python.

 

However, Python also gives a misunderstanding that it can only write simple programs. It is actually a very big misunderstanding that I cannot write a program on the top.

 

With dnsserver, the 30-line program can be used as a good environment for upgrading the trial environment.

 

In addition, if the port number is less than 1000 in Linux, the execution of the program requires system permissions. Otherwise, an exception is thrown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.