Daniel
Daniel

Reputation: 439

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.

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).

What I've done so far is to setup a trigger within the UpdatePanel, like this:

<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.

Any piece of feedback or advice regarding updating of messages is appreciated.

Thank you!

Upvotes: 1

Views: 695

Answers (3)

as-cii
as-cii

Reputation: 13019

If you're using WCF you could implement a CallbackContract that the server calls whenever a message from other clients arrive.

Upvotes: 1

Iain
Iain

Reputation: 11234

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?

Upvotes: 2

Guffa
Guffa

Reputation: 700182

As the HTTP protocol doesn't support server push, you have to poll the server for changes. 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. It only updates when you have called the Update method on the server side to trigger it.

Upvotes: 2

Related Questions