Previous: ASP. NET SignalR with LayIM2.0 Easy implementation of the web chat room (a) of the grassroots data building, let the data Live (data acquisition)
We have completed the initial interface of the construction work, this article will introduce the core of IM, is the SIGNALR hub class. The entire instant messaging mechanism is based on it. As for the principle I also no longer explain, said is not as good as a professional article. So we look directly at the business, on the code. Part of the principle in the article ASP. SignalR and Layim, easy to implement the website customer service chat room (ii) to achieve chat room connection (at that time is the LayIM1.0 version). The principle is the same, but this time I pulled out the server side separately, in order to prevent the server side and the UI side over-coupling, split inconvenient. Go to the Chase:
Open the project Layim.chatserver, and the new Layimhub class inherits from the hub. The core method (where you want to add a microsoft.aspnet.signalr.core,microsoft.aspnet.signalr.systemweb reference) is as follows:
The top three rewrite methods at a glance, it is clear that through these methods, the client can easily know their connection status. We mainly look at the bottom four methods.
- Single Chat connection (clienttoclient): This method is when the user clicks on a person's avatar to open the chat interface, to invoke the method, the purpose is to make the current chat two people assigned to a group. (Of course: clients.client (ConnectionID) is the real way to send a message to a Client), I use the principle here is the group, even if it is two people chatting, the equivalent of a group of only two people, so, two people and multi-personal chat principle is the same. The text is a little abstract, draw a picture people should understand
Is that user A wants to chat with User B to open the process of Chat window, similarly if B happens to also open a window, then the group friend_10001_10000 inside is a and b two clients, then they send the message is that they two people can receive. The reason I sent the message back to myself, because, so that the client can know that my message was sent successfully, because Layim when the client sends a message has been processed, directly add the message to the chat box, but the server may not receive. So there may be a client crazy message, but the server side (the other side) is not receiving a situation. There is another case, a, B is online, but what about the chat window that does not open a? Here first sells a xiaoguanzi, relates to the behind the online personnel statistic mechanism. With this can do a lot of things, as long as the client is involved in whether the online can be used.
Then we reference ChatServer.dll on the UI side, new startup (if not), the code is as follows:
usingMicrosoft.AspNet.SignalR;usingMicrosoft.owin;usingOwin; [Assembly:owinstartupattribute (typeof(Layim_signalr_chat.v1._0.startup))]namespacelayim_signalr_chat.v1._0{ Public Partial classStartup { Public voidConfiguration (Iappbuilder app) {//Configureauth (app);App. Map ("/layim", map = { varHubconfiguration =Newhubconfiguration () {Enablejsonp=true }; Map. RUNSIGNALR (hubconfiguration); }); } }}
The page needs to refer to Jquery.js,signalr.js,/layim/hubs (this is the client Agent auto-generated), in addition, I wrote a simple service call package Hub.js, first run the project to see if the auto-generated code: (/HTTP/ Localhost:8496/layim/hubs)
/*! * ASP. * SignalR JavaScript Library v2.1.2 * http://signalr.net/* Copyright Microsoft Open Technologies, Inc. All rights reserved. * Licensed under the Apache 2.0 * https://github.com/SignalR/SignalR/blob/master/LICENSE.md **////<reference path= ". \.. \signalr.client.js\scripts\jquery-1.6.4.js "/>///<reference path= "Jquery.signalR.js"/>(function($, window, undefined) {///<param name= "$" type= "JQuery"/>"Use Strict"; if(typeof($.SIGNALR)!== "function") { Throw NewError ("SIGNALR:SIGNALR is not loaded. Ensure Jquery.signalr-x.js is referenced before ~/signalr/js. "); } varSignalR =$.signalr; functionMakeproxycallback (Hub, callback) {return function () { //Call the client hub methodcallback.apply (Hub, $.makearray (arguments)); }; } functionregisterhubproxies (instance, shouldsubscribe) {varkey, Hub, Memberkey, Membervalue, Subscriptionmethod; for(Keyinchinstance) { if(Instance.hasownproperty (key)) {hub=Instance[key]; if(!(Hub.hubname)) {//Not a client hub Continue; } if(shouldsubscribe) {//We want to subscribe to the hub eventsSubscriptionmethod =Hub.on; } Else { //We want to unsubscribe from the hub eventsSubscriptionmethod =Hub.off; } //Loop through all members on the hub and find client hub functions to Subscribe/unsubscribe for(Memberkeyinchhub.client) {if(Hub.client.hasOwnProperty (Memberkey)) {Membervalue=Hub.client[memberkey]; if(!$.isfunction (Membervalue)) { //Not a client hub function Continue; } subscriptionmethod.call (Hub, Memberkey, Makeproxycallback (Hub, Membervalue)); } }}} $.hubconnection.prototype.createhubproxies=function () { varproxies = {}; This. Starting (function () { //Register The hub proxies as subscribed //(instance, shouldsubscribe)Registerhubproxies (proxies,true); This. _registersubscribedhubs (); }). Disconnected (function () { //unsubscribe All hub proxies when we "disconnect". this was to ensure, that we don't re-add functional call backs. //(instance, shouldsubscribe)Registerhubproxies (proxies,false); }); proxies[' Layimhub '] = This. Createhubproxy (' Layimhub '); proxies[' Layimhub '].client = { }; proxies[' Layimhub '].server ={clientsendmsgtoclient:function(message) {returnproxies[' Layimhub '].invoke.apply (proxies[' Layimhub '), $.merge (["Clientsendmsgtoclient"], $.makearray (arguments)); }, Clientsendmsgtogroup:function(message) {returnproxies[' Layimhub '].invoke.apply (proxies[' Layimhub '), $.merge (["Clientsendmsgtogroup"], $.makearray (arguments)); }, Clienttoclient:function(Fromuserid, Touserid) {returnproxies[' Layimhub '].invoke.apply (proxies[' Layimhub '), $.merge (["Clienttoclient"], $.makearray (arguments)); }, Clienttogroup:function(Fromuserid, togroupid) {returnproxies[' Layimhub '].invoke.apply (proxies[' Layimhub '), $.merge (["Clienttogroup"], $.makearray (arguments)); } }; returnproxies; }; Signalr.hub= $.hubconnection ("/layim", {usedefaultpath:false }); $.extend (SignalR, SignalR.hub.createHubProxies ());} (Window.jquery, window));
Auto-generated hubs code
As you can see, the above code server already corresponds to the service side of our custom method. (note here that when we call the server-side method, the initials are lowercase.) )
Client Connection Server Core code:
//connecting to a serverConnectfunction() {$.connection.hub.url=_this.option.serverurl; _this.proxy.proxycs=$.connection.layimhub; $.connection.hub.start ({jsonp:true}). Done (function () { //connecting to a server //the logic before TODO handles the chat interface //console.log (' Custom Connection Server Success method: ' + success '); if(call.ready) { for(vari = 0; i < call.ready.length; i++{Call.ready[i] ({connected:true }); }} console.log (' Connection server succeeded '); }). Fail (function () { //console.log (' Custom Connection Server Success method: ' + success '); if(call.failed) { for(vari = 0; i < call.failed.length; i++{Call.failed[i] ({connected:false }); } } }); },
Unconsciously wrote a flashback, to explain to you, above A and B can connect the precondition is to initialize the connection server to succeed, that is, the client calls the Connect method and then be able to print ' Connection server success '.
Finally, unlike Layim1.0, the Layim2.0 reference JS method has changed, similar to the SEAJS syntax. Therefore, our hub code should be changed to the following form:
Autohub.js
Signalr.2.1.2.min.js
Hub.js
After we have defined the modules in this form, we need to add the modules to the page:
// Custom Modules layui.extend ({ '/scripts/signalr/signalr ', '/scripts/signalr/autohub ',// Auto-generated hub: '/scripts/signalr/hub ', });
Finally, we open the server in the form of use:
Run the project and look at it, print out:
To this end, the connection server work has been completed, summed up:
1. Create a Hub file
2. Modify the corresponding config (startup)
3. Modify the corresponding JS code specification (layui.use)
4. Call the Connect method after the interface is initialized.
This article is here, because the project is still in progress, temporarily can not provide source code, but the idea should be no problem, if there are any questions or comments on the blog, Welcome to comment on the exchange below.
Next trailer :"Beginner" ASP. SignalR with LayIM2.0 Easy implementation of the Web chat Room (iii) to achieve single chat, group chat, send pictures, files.
Want to learn the small partner, can follow my blog Oh, my Qq:645857874,email:[email protected]
The ASP. SignalR and LayIM2.0 make it easy to implement the chatserver of the web chat room (ii), connect to the server, and note the considerations.