简体   繁体   English

不断更新聊天消息

[英]Continuously updating chat messages

I'm creating a very simple chat application. 我正在创建一个非常简单的聊天应用程序。 It has an ASP.NET web page as front-end and a WCF service as back-end for storing the messages to a database. 它具有一个ASP.NET网页作为前端,而WCF服务作为后端用于将消息存储到数据库。

Everything works great except one thing; 除了一件事情,一切都很好。 when Browser A enters a chat message I want Browser B to see the message as soon as possible (yeah, I know, that's the purpose of a chat). 当浏览器A输入聊天消息时,我希望浏览器B尽快看到该消息(是的,我知道,这就是聊天的目的)。

What I've done so far is to setup a trigger within the UpdatePanel, like this: 到目前为止,我所做的是在UpdatePanel中设置触发器,如下所示:

<Triggers>
    <asp:AsyncPostBackTrigger ControlID="chatTimer" EventName="Tick" />
</Triggers>

which uses a timer: 使用计时器:

<asp:Timer ID="chatTimer" runat="server" OnTick="chatTimer_Tick" Interval="1000" />

Is this the best approach or is there a better, yet simple, way to accomplish updating of messages. 这是最好的方法,还是有更好但更简单的方法来完成消息更新。 One drawback with this solution is that the textbox used to enter chat messages loses focus every time the Tick event runs. 该解决方案的一个缺点是,每次运行Tick事件时,用于输入聊天消息的文本框都会失去焦点。

Any piece of feedback or advice regarding updating of messages is appreciated. 关于消息更新的任何反馈或建议都值得赞赏。

Thank you! 谢谢!

As the HTTP protocol doesn't support server push, you have to poll the server for changes. 由于HTTP协议不支持服务器推送,因此您必须轮询服务器以进行更改。 There are different ways of doing that, but they are all similar to what you are doing. 可以采用不同的方法,但是它们都与您的工作相似。

You can make the update of your update panel optional by setting UpdateMode="Conditional" , that way it won't update (and lose focus) at every timer tick. 您可以通过设置UpdateMode="Conditional"来使更新面板的更新为可选,这样它就不会在每个计时器滴答时更新(并且不会失去焦点)。 It only updates when you have called the Update method on the server side to trigger it. 仅当您在服务器端调用Update方法来触发它时,它才会更新。

Comet is a technique used for this kind of scenario. 彗星是一种用于这种情况的技术。 Although I wouldn't say it is simple. 虽然我不会说这很简单。

Basically the client would hold a long lived connection open to the server, then the server can push data to the browser. 基本上,客户端将保持与服务器的长期连接,然后服务器可以将数据推送到浏览器。

This question is related: Comet implementation for ASP.NET? 这个问题有关: ASP.NET的Comet实现?

如果您使用的是WCF,则可以实现CallbackContract ,服务器每当来自其他客户端的消息到达时就调用该CallbackContract

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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