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" text = "server send" / >
</div>
ASP. net cs code:
protected void Button1_Click(object sender, EventArgs e)
{
if(MyHub.SendMsgAction!=null)
{
Myhub. Sendmsgaction ("server sends 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 = "sent by client" / >
</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 ("sent 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 the 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.