- 服务器端(WinForm)
1.创建WinForm程序 SignalRService
-
添加新项-OWIN Startup类
-
添加GIT包引用
安装两个NuGet包
Microsoft.Owin.SelfHost
Microsoft.AspNet.SignalR.SelfHost -
创建MoveTextHub类,需要继承于: Hub。在类上面添加[HubName(“getMessage”)]Hub的别名,方便前台调用
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
//Hub的别名,方便前台调用
//[HubName("getMessage")]
public class MyHub : Hub
{
/// <summary>
/// 编写发送信息的方法
/// </summary>
/// <param name="name"></param>
/// <param name="message"></param>
public void Send(string name, string message)
{
//调用所有客户注册的本地的JS方法(addMessage)
Clients.All.addMessage(name, message);
}
}
- 设置刚刚创建的Startup
安装一个GetHub包
Microsoft.Owin.Cors
设置刚刚创建的Startup
using Microsoft.Owin.Cors;
using Owin;
namespace SignalRService
{
public class Startup1
{
public void Configuration(IAppBuilder app)
{
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
}
- 主窗体,两个按钮,一个启动,一个停止,还有一个文本框,用于显示输出信息。
代码如下:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Owin.Hosting;
namespace SignalRService
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public IDisposable SignalR { get; set; }
private const string ServerUri = "http://localhost:8888"; // SignalR服务地址
/// <summary>
/// 启动服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnStart_Click(object sender, EventArgs e)
{
BtnStart.Enabled = false;
WriteToConsole("正在启动服务...");
Task.Run(() => { BtnStart.Enabled = !StartServer(); }); // 异步启动SignalR服务
//Task.Run(() => StartServer()); // 异步启动SignalR服务
//Task.Run(() =>
//{
// BtnStart.Enabled = !StartServer();
//bool flag = StartServer();
//BtnStart.Invoke(new Action<bool>((f) => BtnStart.Enabled = !f), flag);
// }); // 异步启动SignalR服务
//BtnStart.Enabled = !StartServer();
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnStop_Click(object sender, EventArgs e)
{
SignalR.Dispose();
Close();
}
/// <summary>
/// 启动SignalR服务,将SignalR服务寄宿在WPF程序中
/// </summary>
private bool StartServer()
{
try
{
SignalR = WebApp.Start(ServerUri); // 启动SignalR服务
}
catch (Exception ex)
{
WriteToConsole(ex.Message);
return false;
}
WriteToConsole("服务已经成功启动,地址为:" + ServerUri);
return true;
}
private delegate void WriteToConsoleDe(string msg);
/// <summary>
/// 将消息添加到消息列表中
/// </summary>
/// <param name="message"></param>
public void WriteToConsole(string message)
{
if (TxtConsole.InvokeRequired)
{
TxtConsole.Invoke(new Action<string>((string msg) => TxtConsole.AppendText(message + Environment.NewLine)), message);
return;
}
TxtConsole.AppendText(message + Environment.NewLine);
}
}
}
- 客户端(HTML)
-
创建Web空程序 SignalRWebApplication
-
添加GIT包
Microsoft.AspNet.SignalR.JavaScript.Client
-
添加HTML页面,命名为:SendMessage.html
-
SendMessage代码如下
<!DOCTYPE html>
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
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.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.2.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 />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + 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
源码下载:https://pan.baidu.com/s/1bpayjT1
转载于:https://www.cnblogs.com/ypeuee/p/8184786.html
相关资源:SignalR2.0Winform版_signalrwinform,signalrwinfrom-C#代码类…