python bottle可以在WINDOWS上的同一地址和端口上运行两个程序

时间:2013-06-11 13:09:57

标签: python windows bottle httpserver socketserver

我刚刚遇到一个关于Windows上的瓶子的奇怪问题。 当我测试我的瓶码时,我发现它可以使用相同的地址和端口在WINDOWS上运行多个相同的程序。但是当您尝试使用相同的地址和端口在Linux或Mac上启动多个相同的程序时,它将报告以下错误:

socket.error: [Errno 48] Address already in use 

我的瓶子代码是:

from bottle import route, run, template

@route('/hello/:name')
def index(name='World'):
    return template('<b>Hello {{name}} </b>', name=name)

run(host='localhost', port=9999)

然后我跟踪代码,从瓶子到wsgiref,并且最终发现问题可能在Python27 \ Lib \ BaseHTTPServer.py中。 我的意思是当我使用以下简单代码时:

import BaseHTTPServer

def run(server_class=BaseHTTPServer.HTTPServer,
        handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
    server_address = ('localhost', 9999)
    print "start server on localhost 9999"
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

run()

在Windows上会发生同样的问题。

但是如果我直接使用socketserver,就像下面的代码一样:

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    print "Start a server on localhost:9999"
    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

同样的问题不会发生,我的意思是即使在窗口上面,当你尝试启动另一个程序时,上面的socketserver代码会报告错误。

socket.error: [Errno 48] Address already in use

我所有的测试都使用了Python 2.7,Windows 7和Centos 5。

所以我的问题是为什么HTTPServer会在Windows上出现这个问题? 我怎样才能让我的瓶子程序在Windows上报告相同的错误,就像在Windows上一样?

1 个答案:

答案 0 :(得分:2)

很抱歉打扰所有人。

我找到了解决方案,就这么简单。 只需将BaseHTTPServer.HTTPServer的属性allow_reuse_address更改为0。

代码应为:

from bottle import route, run, template
import BaseHTTPServer

@route('/hello/:name')
def index(name='World'):
    return template('<b>Hello {{name}} </b>', name=name)

setattr(BaseHTTPServer.HTTPServer,'allow_reuse_address',0)
run(host='localhost', port=9999)