Home > Article > Backend Development > Detailed explanation of ASP.NET using SignalR to establish a persistent connection between the browser and the server
Foreword
The browser accesses the web page through the HTTP protocol. The browser sends a request and the server returns a result. The server passively receives requests. What if we want to reverse the situation and the server actively sends information to the browser?
There are many solutions, such as round robin (the browser periodically asks the server for new data), WebSocket (HTML 5)...
SignalR integrates these technologies, and it automatically identifies which ones the current browser supports method, and then choose the best method. We don’t have to pay attention to these details when developing, SignalR will help us implement it, and SignalR was developed by Microsoft, and its ease of use is its consistent style.
Environment
.NET 4.5 and above, too low.
If the Visual Studio version is too low and there is no SignalR, follow the steps below to add it:
Visual Studio's menu "Tools-> Library Package Manager-> Manage the NuGet package of the solution (after opening the solution only)", search for "SignalR" in the pop-up dialog box.
The Visual Studio 2013 I use does not need to add SignalR manually, it comes with it.
Practical combat
Open Visual Studio (my version is 2013) and create an ASP.NET project.
The first step is to add a "SignalR permanent connection class"
As shown below:
After adding it, we can find that Visual Studio has automatically added some references for us, as well as the Scripts folder (which contains jquery .signalR-2.0.0.js). The initial code of this class is as follows:
public class MyConnection1 : PersistentConnection { protected override Task OnConnected(IRequest request, string connectionId) { return Connection.Send(connectionId, "Welcome!"); } protected override Task OnReceived(IRequest request, string connectionId, string data) { return Connection.Broadcast(data); } }
The second step is to add the "OWIN Startup class"
Then add some code:
public class Startup1 { public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888 app.MapSignalR<MyConnection1>("/myPath"); // myPath 是我们随便写的。 } }
MyConnection1 is the class name created in the first step .
The third step, add a "Web Form"
<textarea id="info" cols="60" rows="10"></textarea> <script src="Scripts/jquery-1.10.2.min.js"></script> <script src="Scripts/jquery.signalR-2.0.0.min.js"></script> <script type="text/javascript"> <!-- var conn = $.connection("/myPath"); conn.start().done(function (data) { $("#info").append("连接成功,connectionId 为: " + data.id + "\r\n"); }); conn.received(function (data) { $("#info").append("收到数据: " + data + "\r\n"); }); //--> </script>
The operation effect is as follows:
Extend it
MyConnection1:
Method OnConnected: When the connection is created.
Method OnReceived: When the data submitted by the client is received, the parameter data is the data it received.
Method OnDisconnected: When the connection is disconnected. It is not used above.
Method OnReconnected: When reconnected. It is not used above.
…
MyConnection1’s Connection property:
Method Send: Send data to the browser, the first parameter is connectionId (string type), and the second parameter is the data to be sent.
Method Broadcast: Send data to all browsers (accurately, all connections).
JS:
var conn = $.connection("/myPath"); Create a connection object.
conn.start().done() start() is the code to be executed after the connection is started and done() is successfully connected.
conn.received() is executed after receiving the data sent by the server.
conn.send() is to send data to the server. It is not used above.
Let’s look at a more complete code:
The above does not mean that some methods are not used. The following example is more complete:
MyConnection1:
protected override Task OnConnected(IRequest request, string connectionId) { return Connection.Send(connectionId, "Welcome!"); } protected override Task OnReceived(IRequest request, string connectionId, string data) { Connection.Send(connectionId, "我收到了:" + data); return Connection.Broadcast("全体注意:我收到了客户端的数据。"); }
Web form code:
<textarea id="info" cols="60" rows="10"></textarea> 要发送到服务器的消息:<input type="text" id="msg" size="20" /> <input type="button" value="发送消息" onclick="javascript: conn.send($('#msg').val());" /> <script src="Scripts/jquery-1.10.2.min.js"></script> <script src="Scripts/jquery.signalR-2.0.0.min.js"></script> <script type="text/javascript"> <!-- var conn = $.connection("/myPath"); conn.start().done(function (data) { $("#info").append("连接成功,connectionId 为: " + data.id + "\r\n"); }); conn.received(function (data) { $("#info").append("收到数据: " + data + "\r\n"); }); //--> </script>
So far, everyone may not be interested. Where does the server actively send data? ? ?
We are now making a timing program, and the server sends data to the browser regularly.
Create a new Global.asax (global application class) (this does not mean that these codes can only be run in Global.asax, we only put them here to test scheduled execution).
Add the following code:
protected void Application_Start(object sender, EventArgs e) { Timer timer = new Timer(5000); timer.Elapsed += timer_Elapsed; timer.Start(); } void timer_Elapsed(object sender, ElapsedEventArgs e) { var context = GlobalHost.ConnectionManager.GetConnectionContext<MyConnection1>(); context.Connection.Broadcast("我在 " + DateTime.Now.ToString() + " 主动向浏览器发送数据。"); }
The effect is as follows:
For the above code, we use context.Connection.Broadcast. If it is sent for a certain connection, use the Send method, which requires connectionId, but which connectionId to choose is a matter of business level, not a problem.
Summary
The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.
For more detailed explanations on how ASP.NET uses SignalR to establish a persistent connection between the browser and the server, please pay attention to the PHP Chinese website!