When developing a web application, we sometimes need to push the server information to the client. A common scenario is the Weibo application. You need to push a user's real-time message to the Web end, that is, the user's timeline for updating the user.
The general solution is long polling, which can be used by browsers that support XMLHttpRequest, so that it has a wide range of applicability. The processing capability of the server is important. It is best to use non-block concurrency similar to node. js. GitHub has a project signalr that simplifies server side push in Asp.net. To use signalr, We need to search for signalr in nuget and install it.
After the installation is complete, we can use signalr. Let's first look at the implementation of the client:
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">
the server side is also very simple:
Public class microblogserver: hub, idisconnect {Private Static dictionary <string, bool> cancelqueue = new dictionary <string, bool> (); Public void refreshtimeline (string UID) {cancelqueue. add (this. context. connectionid, false); var msgtask = new task (new action <Object> (pushusermessage), UID); msgtask. start ();} private void pushusermessage (Object UID) {While (true) {If (cancelqueue [this. context. con Nectionid]) {cancelqueue. remove (this. context. connectionid); return;} string MSG = getnewmessage (UID. tostring (); caller. newmessage (MSG); // push new message to client string notice = getsystemnotification (); If (! String. isnullorempty (Notice) clients. required y (Notice) ;}} public system. threading. tasks. task disconnect () {If (cancelqueue. keys. contains (this. context. connectionid) {cancelqueue [this. context. connectionid] = true;} return NULL;} # region user message generator private string getnewmessage (string UID) {thread. sleep (3000); Return string. format ("Message from XXX to {0} ({1})", uid, datetime. now);} private string getsystemnotification () {If (new random (). next (6)> = 5) Return "system will shutdown for maintenance"; else return string. empty ;}# endregion}