2016-07-04 45 views
0

我想用python製作一個使用龍捲風的遊戲服務器。龍捲風如何與wsgi一起使用WebSockets

問題是WebSocket似乎不能與wsgi一起使用。

wsgi_app = tornado.wsgi.WSGIAdapter(app) 
server = wsgiref.simple_server.make_server('', 5000, wsgi_app) 
server.serve_forever() 

尋找低谷的計算器,Running Tornado in apache這個答案後,我已經更新了我的代碼使用HTTPServer,其使用WebSockets工作。

server = tornado.httpserver.HTTPServer(app) 
server.listen(5000) 
tornado.ioloop.IOLoop.instance().start() 

然而,當我使用的HttpServer,一個錯誤出現說:TypeError: __call__() takes exactly 2 arguments (3 given)

尋找這件事在互聯網上,我發現了一個問題的答案在這裏: tornado.wsgi.WSGIApplication issue: __call__ takes exactly 3 arguments (2 given)

但添加後tornado.wsgi.WSGIContainer約在app,錯誤依然存在。

我該如何解決這個問題?或者有什麼辦法可以用wsgi來使用龍捲風網絡套接字。

這裏是我的代碼的時刻:

import tornado.web 
import tornado.websocket 
import tornado.wsgi 
import tornado.template 
import tornado.httpserver 
#import wsgiref.simple_server 
import wsgiref 

print "setting up environment..." 

class TornadoApp(tornado.web.Application): 
    def __init__(self): 

     handlers = [ 

      (r"/chat", ChatPageHandler), 
      (r"/wschat", ChatWSHandler), 
      (r"/*", MainHandler) 

     ] 

     settings = { 

      "debug" : True, 
      "template_path" : "templates", 
      "static_path" : "static" 

     } 

     tornado.web.Application.__init__(self, handlers, **settings) 

class MainHandler(tornado.web.RequestHandler): 
    def get(self): 
     self.render("test.html", food = "pizza") 

class ChatPageHandler(tornado.web.RequestHandler): 
    def get(self): 
     self.render("chat.html") 

class ChatWSHandler(tornado.websocket.WebSocketHandler): 
    connections = [] 

    def open(self, *args): 
     print 'a' 
     self.connections.append(self) 
     print 'b' 
     self.write_message(u"@server: WebSocket opened!") 
     print 'c' 

    def on_message(self, message): 
     [con.write_message(u""+message) for con in self.connections] 

    def on_close(self): 
     self.connections.remove(self) 

print "done" 

if __name__ == "__main__": 
    app = TornadoApp() 
    server = tornado.httpserver.HTTPServer(tornado.wsgi.WSGIContainer(app)) 
    server.listen(5000) 
    tornado.ioloop.IOLoop.instance().start() 

感謝在advace!非常感謝。

回答

1

HTTPServer需要tornado.web.Application,這與WSGI應用程序(您可以使用WSGIContainer)不一樣。

如果你需要WSGI和websockets,你可以在兩個獨立的進程中使用你選擇的IPC機制來運行它們(並且使用真正的WSGI服務器而不是Tornado的WSGIContainer)。如果您需要在同一過程中執行這些操作,則可以使用FallbackHandler

wsgi_container = tornado.wsgi.WSGIContainer(my_wsgi_app) 
application = tornado.web.Application([ 
    (r"/ws", MyWebSocketHandler), 
    (r".*", FallbackHandler, dict(fallback=wsgi_container), 
]) 
+0

什麼是'my_wsgi_app'? –

+0

這就是您正在構建的應用程序,您使用的任何WSGI框架的結果。你上面粘貼的應用程序是純粹的龍捲風;如果這是您的應用程序的外觀,則無需獲取與WSGI相關的任何內容。如果您使用像Flask這樣基於WSGI的框架,您只需要WSGI。 –

+0

啊,我明白了!謝謝。我會很快嘗試。 –