异步Servlet客户端、服务器推送
大家好,我想处理一些服务器推送。我有一个异步 Servlet 处理某些内容,将其推送到客户端,然后处理其他内容并将其再次推送到客户端(同一连接)。服务器仅返回数据(在本例中为 Json,但这并不重要)仅此而已。
所以我的问题是客户。我如何为此建立一个客户端?例如,如果我使用 JQuery 发出 ajax 请求,我如何对第一个响应后出现的数据做出反应?
为了更清楚地说明我想要什么,这里有一个比较:使用 websockets,我有 onmesssage 方法。
websocket ws = new WebSocket("ws://myserver.com");
ws.onmessage = function(event)
{
var x = event.data
.... // some other code here
}
所以我想要的只是一个 onmessage 方法:)。我想这不像网络套接字那么容易,但也许有人有一个想法。
问候亚历克斯
Hello guys i want to process some server pushes. I have an asynchronous servlet processing something, pushing it to the client and then it processes something else and pushes it again to the client (same connection). The servet just returns data (Json in this case, but that does not really mather) nothing more.
So my problem is the client. How do i build a client for that? If i make an ajax request with JQuery for example how can i react on the data that comes after the first response?
To make it more clear what i want here is a comparison : With websockets i have the method onmesssage.
websocket ws = new WebSocket("ws://myserver.com");
ws.onmessage = function(event)
{
var x = event.data
.... // some other code here
}
So all i want is a onmessage Method :). I guess it is not that easy as it is with websockets but maybe someone has an idea.
Greetings Aleks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以让服务器生成响应,该响应由客户端加载到隐藏的 iframe 中。生成的响应将偶尔包含调用“外部”(包含文档)的 JavaScript 语句。您可以使用
parent
获取包含文档。但请注意,这种技术相当黑客(至少在我看来)。您可能需要重新考虑仅使用 XMLHttpRequest,特别是因为它为您提供了简单而强大的错误处理。您可以执行更多请求(而不是附加到服务器端的“旧”响应)。这可能会带来额外的延迟,但 iframe 技巧在实践中确实很麻烦。
You can have your server generate a response which is loaded into an hidden iframe by the client. The generated response would contain occasional JavaScript statements which call to the "outside" (the containing document). You can get your hands on the containing document using
parent
.But please not that this technique is pretty hackish (at least it seems to me). You might want to re-consider just using the XMLHttpRequest, especially because it gives you simple and robust error handling. You can just do more requests (instead of appending to an "old" response on the server side). This will probably introduce additional lag, but that iframe trick is really troublesome in practice.