简体   繁体   中英

How do I run Klein with twisted?

I'm trying to run klein with twisted, so I can run twisted scripts on different paths (exp: example.com/example1 , example.com/example2 ). So I made a simple script:

from klein import run, route, Klein
from twisted.internet import reactor
from twisted.web import proxy, server
from twisted.python import log

@route('/example')
def home(request):
    site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, b''))
    reactor.listenTCP(80, site)
    reactor.run()

run("My_IP_Address", 80)

But whenever I run this script I get an Error: twisted.internet.error.CannotListenError: Couldn't listen on any:80: [Errno 98] Address already in use. I'm very new to Klein, and I'm not sure how it works, Could anybody tell me what it is I'm doing wrong? thanks!

This exception that you're getting seems fairly clear it says:

Couldn't listen on any:80: [Errno 98] Address already in use.

it happens when port number you're trying to use is already used by some other services. This other service can be either something other than Twisted or two Twisted services. I'm going to assume you dont have anything else listening on port 80 (eg nginx or apache or some other web server, note that 80 is default HTTP port so many services can be listening there) and that your problem is caused by starting two twisted web services.

In your case you are trying to start two services listening on one port.

run("My_IP_Address", 80)

starts one service listening on port 80.

After receiving request on /example route you're trying to start another service on this same port:

site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, b''))
reactor.listenTCP(80, site)
reactor.run()

this does not make logical sense, you can't have two services running on same port. This is why you get this exception. Also your call to reactor.run() is useless, run() imported from klein already starts reactor.

If you really do need to start some server after some request (this seems like very unusual use case) start it on a different port. But maybe you should simply start with official documentation and examples there?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM