SignalR's alternative implementation skills and signalr's alternative skills
A long time ago, I published an article titled "learn three implementation methods of SignalR through three demos". In that article, I described in detail the commonly used SignalR implementation methods in WEB applications, today, we use SignalR to implement other usage, such as communication between B/S and C/S, for example, communication between C/S and C/S.
I. Communication between B/S and C/S (ASP. NET broadcasts messages to Winform)First, the effect is as follows:
[HubName ("myHub")] public class MyHub: Hub {public static Action <string> SendMsgAction = null; public MyHub () {SendMsgAction = new Action <string> (SendMsg);} private void SendMsg (string msg) {Clients. all. recvMsg (msg);} [HubMethodName ("broadcast")] public void Broadcast (string msg) {if ("broadcast ". equals (Context. queryString ["identity"]) // only a broadcaster can broadcast messages {SendMsg (msg) ;}} public override System. threading. tasks. task OnConnected () {return base. onConnected ();} [HubMethodName ("testConnect")] public void TestConnect () {System. diagnostics. debug. write ("ddd ");}}
ASP. NET page: (the server control is used for sending to the server)
<div>
Broadcast message: <input type = "text" id = "txtmsg" runat = "server" />
<asp: Button ID = "Button1" runat = "server" OnClick = "Button1_Click" Text = "Server sends" "/>
</ div>
ASP. net cs code:
protected void Button1_Click (object sender, EventArgs e)
{
if (MyHub.SendMsgAction! = null)
{
MyHub.SendMsgAction ("The server sends a message-" + txtmsg.Value);
}
}
Note that the MyHub instance is generated only when there is a connection, and we cannot directly obtain the MyHub instance on the server. Therefore, when using the MyHub constructor, expose SendMsg to the static SendMsgAction delegate so that the server can determine whether to send messages directly by checking whether SendMsgAction has a subscription. This is a clever method. If you have a better method, please contact us.
The method for sending via a browser is the same as described in the previous article. The proxy mode is used here. The ASP. NET page code is as follows: (not described too much)
<script src = "<% = ResolveUrl (" ~ / Scripts / jquery-1.10.2.min.js ")%>" type = "text / javascript"> </ script>
<script src = "<% = ResolveUrl (" ~ / Scripts / jquery.signalR-2.2.2.min.js ")%>" type = "text / javascript"> </ script>
<script src = "<% = ResolveUrl (" ~ / signalr / hubs ")%>" type = "text / javascript"> </ script>
<div>
Broadcast message: <input type = "text" id = "txtmsg2" />
<input type = "button" id = "btnSend" value = "client sends" />
</ div>
<script type = "text / javascript">
$ (function () {
var myhub = $ .connection.myHub;
$ .connection.hub.qs = {"identity": "broadcast"};
$ .connection.hub.start (). done (function () {
$ ("# btnSend"). click (function () {
var msg = $ ("# txtmsg2"). val ();
myhub.server.broadcast ("Client sends message-" + msg)
.done (function () {
alert ("Send successfully!");
}). fail (function (e) {
alert (e);
$ ("# txtmsg2"). focus ();
});
});
});
});
</ script>
Note: when defining the MyHub class, according to The CSharp code specification, the first letter of the Class Name and method name is capitalized, but the agent JS class and method names automatically generated by JS will become the JS life specification, that is, the first letter of the function name is lowercase, such as: MyHub --> myHub, therefore, to facilitate JavaScript calls, use the HubName and HubMethodName features when defining the Hub class and specify a uniform name.
To receive messages from the winform client, follow these steps:
1. Install SignalR. Client components through NuGet
2. Winform CS code:
public partial class Form1: Form
{
private HubConnection connection = null;
private IHubProxy hubProxy = null;
private System.Threading.SynchronizationContext syncContext = null;
public Form1 ()
{
InitializeComponent ();
syncContext = System.Threading.SynchronizationContext.Current;
}
private void Form1_Load (object sender, EventArgs e)
{
CreateHubConnection ();
}
/// <summary>
/// Create Hub proxy class and start
/// </ summary>
private void CreateHubConnection ()
{
connection = new HubConnection ("http: // localhost: 3510 / signalr"); // SignalR server address
hubProxy = connection.CreateHubProxy ("MyHub");
hubProxy.On <string> ("RecvMsg", RecvMsg); // Subscribe to receive messages
connection.Start (). Wait ();
}
/// <summary>
/// Receive messages from SignalR server
/// </ summary>
/// <param name = "msg"> </ param>
private void RecvMsg (string msg)
{
syncContext.Post ((o) => {
textBox1.Text + = string.Format ("{0: yyyy-MM-dd HH: mm: ss} {1} \ r \ n", DateTime.Now, o);
}, msg);
}
private void Form1_FormClosed (object sender, FormClosedEventArgs e)
{
connection.Dispose ();
}
private void button1_Click (object sender, EventArgs e)
{
hubProxy.Invoke ("TestConnect"); // Call the method of SignalR server
}
}
The code above shows that the method is basically the same as that of the JS proxy class generated on the ASP. NET page. It interacts with the server through the proxy class and communicates with the server through the HTTP protocol.
2. Communication between C/S and C/S (winform and winform)In fact, in essence, the server is still B/S, but we have adopted SignalR self Host (OWIN self Host is used in it), that is, boarding the website to winform, we only need to use winform to perform more operations. The effect is as follows:
Public class Startup {public void Configuration (IAppBuilder app) {app. MapSignalR ();}}
3. Write the OWIN boarding code. MyHub is the same as the above, so it is no longer posted
public partial class Form1: Form
{
private IDisposable webHost = null;
public static Form1 Current = null;
public Form1 ()
{
InitializeComponent ();
this.Text = "SignalR Winform server";
Current = this;
}
private void Form1_Load (object sender, EventArgs e)
{
try
{
webHost = WebApp.Start <Startup> ("http: // localhost: 3512");
label2.Text = "http: // localhost: 3512";
}
catch (Exception ex)
{
MessageBox.Show (ex.Message);
}
}
private void Form1_FormClosed (object sender, FormClosedEventArgs e)
{
try
{
webHost.Dispose ();
}
catch
{}
}
private void button1_Click (object sender, EventArgs e)
{
if (MyHub.SendMsgAction! = null)
{
MyHub.SendMsgAction (textBox1.Text);
}
}
public void ShowMsg (string msg)
{
this.Invoke (new MethodInvoker (() => {
listBox1.Items.Add (msg);
}));
}
}
Note the following details:
1. After Microsoft. AspNet. SignalR is installed, the Sciprts folder will be generated in the project, which can be deleted during winform project;
2. install Microsoft. aspNet. after SignalR Self Host, compilation may be normal, but when running it, Zhu may find the matched OWin assembly, which is due to the OWIN version issue, you only need to install the specified OWIN version separately.