Singalr初学

   [HubName("djwChat")]

    public class ChatHub:Hub

    {

        public void Send(string name)

        {

            //动态表达式

            Clients.All.addMsgToPage(name);

                      

        }



    }

owin配置非常重要。

[assembly: OwinStartup(typeof(SingalRTest.Startup))]

namespace SingalRTest

{



    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {           

            app.MapSignalR();

        }

    }

}
  <appSettings>

    <add key="webpages:Version" value="2.0.0.0" />

    <add key="webpages:Enabled" value="false" />

    <add key="PreserveLoginUrl" value="true" />

    <add key="ClientValidationEnabled" value="true" />

    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="owin:AppStartup" value="SingalRTest.Startup, SingalRTest" />

    <!--<add key="owin:AutomaticAppStartup" value="true" />-->

  </appSettings>

如果没有

[assembly: OwinStartup(typeof(SingalRTest.Startup))],需要在appSettings里配置节点
        $(function () {



            //创建代理

            var chat = $.connection.djwChat;



            chat.client.addMsgToPage = function () {

                //2、服务端通知客户端 do something 

            };



            $("#send").click(function () {

                chat.server.send("msg");

                //1、发送消息到服务端,调用服务端的Send方法

            });



            $.connection.hub.start();



        });

 

 PersistentConnection长连接类的使用方法
public class MyConnection:PersistentConnection

    {

        protected override System.Threading.Tasks.Task OnReceived(IRequest request, string connectionId, string data)

        {

             data = string.Format("数据是:{0} 时间是:{1}", data, DateTime.Now.ToString());

             return Connection.Send(connectionId, data);

        }

    }

同样是owin启动配置

[assembly: OwinStartup(typeof(SingalRTest.Startup))]

namespace SingalRTest

{



    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            // Any connection or hub wire up and configuration should go here 

            //app.MapSignalR();

            

            app.MapSignalR<MyConnection>("/随便写");//必须是/开头,自定义路径。

        }

    }

}
    <script type="text/javascript">

        $(function () {

            

            var connection = $.connection('/随便写');//保持和后台自定义路径相同

            connection.received(function (data) {

                $('#messages').append('<li>' + data + '</li>');

            });



            connection.start();



            $("#broadcast").click(function () {

                connection.send($('#msg').val());

            });

            $("#btnStop").click(function () {

                connection.stop();

            });

        });



    </script>

 

 

你可能感兴趣的:(in)