Chapter 4 SignalR self-managed host and Chapter 4 signalr-managed host
Chapter IV SignalR self-managed host
The SignalR server is usually used in Asp.. Net application, but it can also run as a self-managed host (like a console application or a Windows Service) Like Signal2.0, the self-built library is based on. net open Web interface (OWIN) to build. OWIN defines the abstract interface between the. Net Web server and the Web application, decouples the Web application from the server, so that the OWIN can establish a self-managed host outside of IIS.
Why don't we host SignalR in IIS? For the following reasons:
1) You cannot install the IIS environment or use IIS, such as a server host without IIS.
2) Considering the performance, you need to avoid additional IIS overhead.
3) SignalR runs in a Windows service or Azure working role, or is used for other existing applications.
(IIS can be installed on windows operating system servers. Non-windows operating system servers cannot use -_-!!!; If SinglaR occupies more resources in IIS or is self-managed, it must be tested to ensure the running efficiency and performance ;)
1. Set the project:
In this example, you will create a server hosted in the console application. Of course, it is also feasible to host it in the Windeos service and Azure working role.
1) Run VS2013 as an administrator. Create a console application named "SignalRSelfHost" and click OK.
2) Open the package management console.
3) enter the command in the console
Install-Pagkage Microsoft. AspNet. SignalR. SelfHost |
This command adds the SingalR self-built library to the project.
4) continue to enter the following command on the console:
Install-Package Microsoft. Owin. Cors |
This command adds the OWIN core library to the project, because the SignalR host runs in different domains with the Web Client, this library will be used for cross-origin support. Because the SignalR service and the Web Client run on different ports, this means that if you want to communicate between these components, you must start the cross-origin feature in these components.
5) Replace the code in Program. cs:
Using System; Using Microsoft. AspNet. SignalR; Using Microsoft. Owin. Hosting; Using Owin; Using Microsoft. Owin. Cors; Namespace SignalRSelfHost { Class Program { Static void Main (string [] args) { String url = "http: // localhost: 8080 "; Using (WebApp. Start (url )) { Console. WriteLine ("Server running on {0}", url ); Console. ReadLine (); } } } Class Startup { Public void Configuration (IAppBuilder app) { App. UseCors (CorsOptions. AllowAll ); App. MapSignalR (); } } Public class MyHub: Hub { Public void Send (string name, string message) { Clients. All. addMessage (name, message ); } } } |
The code above contains three classes:
A: Program, which contains the master path of the Mian method definition execution. In this method, the local host is specified to enable port 8080 to start the Web application. Of course, you can also implement SSL to further improve security.
B: Startup, including the configuration of the SignalR server (in this example, only the UserCors configuration class is used and MapSignalR is called to create a route ing for the hub.
C: MyHub, The Hub implementation class of SignalR, used to provide client services. This class also contains a method: Send, which is used to broadcast received client messages to other connected clients.
6) Compile and run the program. The server address is displayed on the console.
7) if the execution fails, in addition to the System. Relection. TargetInvocationException error, you must give the Administrator the permission to re-run VS2013 and re-compile and run it.
8) Close the console program before proceeding to the next step.
2. access the server using a JavaScript client:
In this example, you will use the same JS client as the Getting Started tutorial. I just made a modification, that is, defining the hub URL as a self-hosted host. The server does not necessarily use the same URL as the connection address (refer to reverse proxy and load balancing ), therefore, the URL must be defined.
1) In Solution Explorer, add an Asp. Net Web application, name it "JavascriptClient", and then confirm.
2) create a project with an empty template.
3) in the package management console, select the "JavaScriptClient" project from the default project drop-down list and execute the following command:
Install-Package Microsoft. AspNet. SignalR. JS |
This command installs the SignalR and jQuery libraries required by the client.
A new HTML page named default.html"
5) use the following code to replace the Html content. You also need to check whether the script paths referenced in the Code are consistent.
<! DOCTYPE html> <Html> <Head> <Title> SignalR Simple Chat </title> <Style type = "text/css"> . Container { Background-color: #99 CCFF; Border: thick solid #808080; Padding: 20px; Margin: 20px; } </Style> </Head> <Body> <Div class = "container"> <Input type = "text" id = "message"/> <Input type = "button" id = "sendmessage" value = "Send"/> <Input type = "hidden" id = "displayname"/> <Ul id = "discussion"> </ul> </Div> <! -- Script references. --> <! -- Reference the jQuery library. --> <Script src = "Scripts/jquery-1.10.2.min.js"> </script> <! -- Reference the SignalR library. --> <Script src = "Scripts/jquery. signalR-2.0.3.min.js"> </script> <! -- Reference the autogenerated SignalR hub script. --> <Script src = "http: // localhost: 8080/signalr/hubs"> </script> |
<! -- Add script to update the page and send messages. --> <Script type = "text/javascript"> $ (Function (){ // Set the hubs URL for the connection $. Connection. hub. url = "http: // localhost: 8080/signalr "; // Declare a proxy to reference the hub. Var chat = $. connection. myHub; // Create a function that the hub can call to broadcast messages. Chat. client. addMessage = function (name, message ){ // Html encode display name and message. Var encodedName = $ ('<div/> '{.text(name}.html (); Var encodedMsg = $ ('<div/> 'hangzhou.text(message0000.html (); // Add the message to the page. $ ('# Discussion'). append (' <li> <strong> '+ encodedName + '</Strong>: & nbsp;' + encodedMsg + '</li> '); }; // Get the user name and store it to prepend to messages. $ ('# Displayname'). val (prompt ('enter your name :','')); // Set initial focus to message input box. $ ('# Message'). focus (); // Start the connection. $. Connection. hub. start (). done (function (){ $ ('# Sendmessage'). click (function (){ // Call the Send method on the hub. Chat. server. send ($ ('# displayname'). val (), $ (' # message'). val ()); // Clear text box and reset focus for next comment. $ ('# Message'). val (''). focus (); }); }); }); </Script> </Body> </Html> |
Note: The Code of the next line contains the basic connection URL of SignalR:
$. Connection. hub. url = "http: // localhost: 8080/signalr "; |
6) Right-click the solution and set multiple startup projects to start
7. Right-click default.html and set it to the start page.
8) running the project will pop up the console service and Web page. If the Web page is executed before the console server starts, you need to refresh the page again.
(9) You can enter the user name and open multiple browsers to test multi-user chat rooms. ^-^