using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using Microsoft.Owin; //NuGet安装 using Microsoft.Owin.Cors; using Microsoft.Owin.Hosting; using Microsoft.SqlServer.Server; using System.Net; //HttpListenerz只需要安装不需要using //using Microsoft.Owin.Host.HttpListener; //[assembly: OwinStartup(typeof(SingalrSelfHost.Startup))] namespace SingalrSelfHost { class Program { static void Main(string[] args) { string url = @"http://localhost:8080"; using (WebApp.Start(url)) { Console.WriteLine("server running on {0}",url); Console.ReadLine(); } } } class Startup { public void Configuration(IAppBuilder app) { app.UseCors(CorsOptions.AllowAll); app.MapSignalR(); } } public class MyHub : Hub { public void Send(string name, string message) { Clients.All.addMsg(name, message); } } }
控制台程序不需要给Startup添加[assembly: OwinStartup(typeof(SingalrSelfHost.Startup))]特性,也不需要在appSetting里面配置。
<script src="Scripts/jquery-1.6.4.min.js"></script> <script src="Scripts/jquery.signalR-2.2.0.min.js"></script> <script src="http://localhost:8080/signalr/hubs"></script> <script type="text/javascript"> $(function () { $.connection.hub.url = "http://localhost:8080/signalr"; var chat = $.connection.myHub; chat.client.addMsg = function (name, message) { var encodedName = $('<div />').text(name).html(); var encodedMsg = $('<div />').text(message).html(); $('#discussion').append('<li><strong>' + encodedName + '</strong>: ' + encodedMsg + '</li>'); }; $('#displayname').val(prompt('Enter your name:', '')); $('#message').focus(); $.connection.hub.start().done(function () { $('#sendmessage').click(function () { chat.server.send($('#displayname').val(), $('#message').val()); $('#message').val('').focus(); }); }); }); </script>
静态页html可以用js直接访问。
补充:
owinhost启动方式
static void Main(string[] args) { using (Microsoft.Owin.Hosting.WebApp.Start<Startup>("http://localhost:8080")) { Console.WriteLine("host is running"); Console.ReadLine(); } }