The examples in this article describe the Serverpush usage in asp.net. Share to everyone for your reference. The specific analysis is as follows:
What is Serverpush, the server to the client "push", in fact, is "long connection"
Only the browser request server, the server to the browser to respond to data, will not actively push data to the browser, this is a security consideration, but also improve the performance of the server, if the server to the browser to actively push data, it is necessary to use the Serverpush technology simulation implementation.
As an example:
Message implementations are sent to each other through two pages, and messages are placed in the database.
<summary>///ServerPush1 Summary description///</summary> public class Serverpush1:ihttphandler {public void Pr Ocessrequest (HttpContext context) {context.
Response.ContentType = "Application/json"; String action = context.
Request["Action"]; if (action = = "send")//Send {string me = context.
Request["Me"]; String tousername = context.
request["Tousername"]; String msg = context.
request["MSG"]; Sqlhpler.executenonquery ("INSERT into T_msgs (fromusername,tousername,msg) VALUES (@FromUserName, @ToUserName, @Msg)" , New SqlParameter ("@FromUserName", Me), New SqlParameter ("@ToUserName", Tousername), New SqlParameter ("@Msg", M
SG)); Context. Response.Write (New JavaScriptSerializer ().
Serialize (New {Status = "OK"})); else if (action = = "Receive")//login, and continue to query, receive data from the other side {//do a simple example to Serverpush1.ashx?me=sean//please send to Sean's elimination Send me a string me = context.
Request["Me"]; while (true) {DataTable dt = Sqlhpler.executequery ("SELECT Top 1 * from T_msgs WHERE tousername= @ToUserName ", New SqlParameter (" @ToUserName ", Me)); if (dt.
Rows.Count <= 0) {thread.sleep (500); not found, rest 500ms again query, so as to avoid the query pressure on the database, and occupy the Web server CPU resources continue;//the next while else {DataRow row = dt.
Rows[0];
Long id = (long) row["id"];
String fromusername = (string) row["Fromusername"];
String msg = (string) row["MSG"]; After the query to delete the message, otherwise there will be a dead loop, non-stop to the page output the same message sqlhpler.executenonquery ("DELETE from t_msgs WHERE id= @Id", New SqlParameter ("@Id
", id));
Create an anonymous object and save the query to the inside var data = new {Fromusername = fromusername, msg = msg, id = ID}; String json = new JavaScriptSerializer (). Serialize (data)//Converts an anonymous object to the JSON context.
Response.Write (JSON);//Returns the request result to the break in JSON format;
}} else {throw new Exception ("Action error");
}
}
I hope this article will help you with your asp.net programming.