using System;
using Microsoft.AspNet.SignalR;
namespace SignalDemo
{
public class ServerHub : Hub
{
private static readonly char[] Constant =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'
};
/// <summary>
/// 供客户端调用的服务器端代码
/// </summary>
/// <param name="message"></param>
public void Send(string message)
{
var name = GenerateRandomName(4);
// 调用所有客户端的sendMessage方法
Clients.All.sendMessage(name, message);
}
/// <summary>
/// 产生随机用户名函数
/// </summary>
/// <param name="length">用户名长度</param>
/// <returns></returns>
public static string GenerateRandomName(int length)
{
var newRandom = new System.Text.StringBuilder(62);
var rd = new Random();
for (var i = 0; i < length; i++)
{
newRandom.Append(Constant[rd.Next(62)]);
}
return newRandom.ToString();
}
}
}
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(SignalDemo.Startup))]
namespace SignalDemo
{
public partial class Startup
{
#region MyRegion
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
ConfigureAuth(app);
}
#endregion
}
}
using System.Web.Mvc;
namespace SignalDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Chat()
{
return View();
}
}
}
@{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<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>
@section scripts
{
<!--引用SignalR库. -->
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--引用自动生成的SignalR 集线器(Hub)脚本.在运行的时候在浏览器的Source下可看到 -->
<script src="~/signalr/hubs"></script>
<script>
$(function () {
// 引用自动生成的集线器代理
var chat = $.connection.serverHub;
// 定义服务器端调用的客户端sendMessage来显示新消息
chat.client.sendMessage = function (name, message) {
// 向页面添加消息
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// 设置焦点到输入框
$('#message').focus();
// 开始连接服务器
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// 调用服务器端集线器的Send方法
chat.server.send($('#message').val());
// 清空输入框信息并获取焦点
$('#message').val('').focus();
});
});
});
// 为显示的消息进行Html编码
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
using System.Web.Mvc;
using System.Web.Routing;
namespace SignalDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Chat", id = UrlParameter.Optional }
);
}
}
}
public class ServerHub : Hub
{
private static readonly char[] Constant =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z'
};
/// <summary>
/// 供客户端调用的服务器端代码
/// </summary>
/// <param name="message"></param>
public void Send(string message)
{
var name = GenerateRandomName(4);
// 调用所有客户端的sendMessage方法
Clients.All.sendMessage(name, message);
}
/// <summary>
/// 客户端连接的时候调用
/// </summary>
/// <returns></returns>
public override Task OnConnected()
{
Trace.WriteLine("客户端连接成功");
return base.OnConnected();
}
/// <summary>
/// 产生随机用户名函数
/// </summary>
/// <param name="length">用户名长度</param>
/// <returns></returns>
public static string GenerateRandomName(int length)
{
var newRandom = new System.Text.StringBuilder(62);
var rd = new Random();
for (var i = 0; i < length; i++)
{
newRandom.Append(Constant[rd.Next(62)]);
}
return newRandom.ToString();
}
}
/// <summary>
/// 启动SignalR服务,将SignalR服务寄宿在WPF程序中
/// </summary>
private void StartServer()
{
try
{
SignalR = WebApp.Start(ServerUri); // 启动SignalR服务
}
catch (TargetInvocationException)
{
WriteToConsole("一个服务已经运行在:" + ServerUri);
// Dispatcher回调来设置UI控件状态
this.Dispatcher.Invoke(() => ButtonStart.IsEnabled = true);
return;
}
this.Dispatcher.Invoke(() => ButtonStop.IsEnabled = true);
WriteToConsole("服务已经成功启动,地址为:" + ServerUri);
}
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
public override Task OnConnected()
{
//
Application.Current.Dispatcher.Invoke(() =>
((MainWindow)Application.Current.MainWindow).WriteToConsole("客户端连接,连接ID是: " + Context.ConnectionId));
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Application.Current.Dispatcher.Invoke(() =>
((MainWindow)Application.Current.MainWindow).WriteToConsole("客户端断开连接,连接ID是: " + Context.ConnectionId));
return base.OnDisconnected(true);
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
// 允许CORS跨域
//app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public IHubProxy HubProxy { get; set; }
const string ServerUri = "http://localhost:8888/signalr";
public HubConnection Connection { get; set; }
public MainWindow()
{
InitializeComponent();
// 窗口启动时开始连接服务
ConnectAsync();
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSend_Click(object sender, RoutedEventArgs e)
{
// 通过代理来调用服务端的Send方法
// 服务端Send方法再调用客户端的AddMessage方法将消息输出到消息框中
HubProxy.Invoke("Send", GenerateRandomName(4), TextBoxMessage.Text.Trim());
TextBoxMessage.Text = String.Empty;
TextBoxMessage.Focus();
}
private async void ConnectAsync()
{
Connection = new HubConnection(ServerUri);
Connection.Closed += Connection_Closed;
// 创建一个集线器代理对象
HubProxy = Connection.CreateHubProxy("ChatHub");
// 供服务端调用,将消息输出到消息列表框中
HubProxy.On<string, string>("AddMessage", (name, message) =>
this.Dispatcher.Invoke(() =>
RichTextBoxConsole.AppendText(String.Format("{0}: {1}\r", name, message))
));
try
{
await Connection.Start();
}
catch (HttpRequestException)
{
// 连接失败
return;
}
// 显示聊天控件
ChatPanel.Visibility = Visibility.Visible;
ButtonSend.IsEnabled = true;
TextBoxMessage.Focus();
RichTextBoxConsole.AppendText("连上服务:" + ServerUri + "\r");
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有