在 Sinatra 应用程序中维护单个持久的 EM 连接
我是一个 EventMachine 新手,所以我的做法可能是完全错误的。我想做的是在应用程序启动时创建一个 EM 连接(实际上是 Blather 流,但那是 EM::Connection),然后我可以在需要时点击该连接。现在,我能让 Blather 在这个 Sinatra 应用程序中正常工作的唯一方法是每次创建一个新连接,该连接包装在 EM.run 块内。
我一直在尝试确定 async_sinatra 是否有帮助。不过,我实际上并不关心请求是否异步发生。我想这会很好,但我仍然不知道如何保持请求之间的连接。
在我看来最有意义的解决方案是在 Sinatra 配置块内的 EM 块中设置连接,但随后我不确定如何访问它。不过,也许我错过了一些基本的东西。
ps 这最终将在 Heroku 上运行,因此虽然我非常感谢任何见解,但已知可在 Heroku 上运行的解决方案将是最有用的。
编辑:
这似乎正在做我想要的事情,至少在本地:
class Dashboard < Sinatra::Base
configure do
Thread.start do
EM.run do
@@xmpp_stream = Blather::Client.setup('jid', 'password')
@@xmpp_stream.connect
end
end
end
end
I'm a bit of an EventMachine novice, so there's a chance I'm approaching this completely wrong. What I'm trying to do is create an EM connection (actually a Blather stream, but that is an EM::Connection) once when the app starts up, which I can then hit whenever I need to. Right now, the only way I can Blather to work correctly in this Sinatra app is to create a new connection every time, which is wrapped inside a EM.run block.
I've been trying to determine if async_sinatra would help. I don't actually care, though, if the requests happen asynchronously. I suppose it would be nice, but I'm still not seeing how I would persist the connection between requests.
The solution that seems to make the most sense in my brain is to setup the connection in an EM block inside the Sinatra configure block, but then I'm not sure how to get access to it down the road. Perhaps I'm missing something kind of basic, though.
p.s. This will eventually run on Heroku, so while I would greatly appreciate any insight, solutions that are known to work on Heroku will be the most useful.
Edit:
This seems to be doing what I want, locally at least:
class Dashboard < Sinatra::Base
configure do
Thread.start do
EM.run do
@@xmpp_stream = Blather::Client.setup('jid', 'password')
@@xmpp_stream.connect
end
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先是:
这将打开一个到本地主机上端口 4000 的服务器的持久连接,它将存储从该服务器接收到的任何内容,并在通过 Web 浏览器请求索引页面时显示它。
将其保存在“config.ru”文件中并运行:
在我的例子中,端口 4000 上的服务器是(我在 mac os x 上,linux 也有):
只需将我打开的连接替换为您想要的连接即可。
Here is something to start with:
This will open a persistent connection to a server on localhost with port 4000, it will store anything received from it and displays it when the index page is requested via a web browser.
Save this in a "config.ru" file and run this with:
In my case the server on port 4000 was (I am on mac os x, linux also has it):
Just replace the connection I open with what you want.