I’m developing an Asp.Net chat by using Ajax-Wcf Service enabled. It’s a very simple chat engine, where messages dialog means one to one (single user), however I don’t know how to manage (in a best way) notify for new message availability.
For instance, supposing the following scenario:
All time I need to send a new message from a user to another I write javascript code like this:
// btnSend client event handler
MyWcfNamespace.MyWcfClass instance = new ..();
instance.CallMethod("message string", callBackFunction, null);
Well, that’s very simple. Now, from the other side (user which will receive my message), needs for some mechanism in order to know when a new message has been sent. I thought to use an ajax timer to call another wcf Method which return me string message if it is available, or empty string if isn’t,
but I think ther’s a best way to accmplish this.
It would be great if exist some way to register for some wcf event by javascript:
// javascript code:
MyWcfNamespace.MyWcfClass instance = new ..();
instance.OnNewMessageAvailable = myJavascriptCallBackFunction;
// And on CallBack function..
function myJavaScriptCallbackFunction(msg) {
alert('new message arraived:' + msg):
}
Obviously, my wcf service should be implement some static event to manage all notify I needs.
Any suggestions will be appreciated.
Thank you.
With WCF you could do it by using techniques like long polling, to achieve this but obviously this would not be very easy. Look at this example on how to
There are many JS libararies which make this work eassy for you. SignalR is one of them
Look at this Wiki on how to
Update 2
If you are using Wcf 4.5, another way to accomplish this task would be using web sockets. Chat Application requires push based technology rather than pull based technology. Wcf 4.5 give you this power by supporting Web Sockets. Example
Update 3
If you have decided to use Long Polling, then you do not have use async methods. The long polling will work as following.
So instead of using async result(since the call to web service from JS would already be async), you would use normal method with Thread Signalling techniques like WaitOne(for waiting till new request comes) and ManualResetEvent for signalling, some request has come.
Notice, Long polling is far better than polling as response is always up to date.
Look at this implementation of Chat Server using Wcf and Long Polling