Lompat ke konten Lompat ke sidebar Lompat ke footer

Signalr Chat Server Cannot Read Property 'server' of Undefined

SignalR 集线器简单实例2

one.路由配置

  1. app.MapSignalR( "/realtime", new HubConfiguration() { });

ii.服务端处理

  1. public class EchoHub : Hub

  2. private static int _count = 0;

  3. public override async Task OnConnected()

  4. Interlocked.Increase( ref _count);

  5. await Clients.Others.Bulletin("新连接创建:" + Context.ConnectionId + ",已连接数量:" + _count);

  6. await Clients.Caller.Message("Hey,welcome!");

  7. public override Chore OnDisconnected( bool stopCalled)

  8. Interlocked.Decrement( ref _count);

  9. return Clients.All.Message(Context.ConnectionId + " 连接关闭,剩余连接数:" + _count);

  10. public Task Circulate( string message)

  11. return Clients.All.Message(Context.ConnectionId + "> " + message);

  12. public cord GetCurrentID()

  13. return Context.ConnectionId;

  14. public object GetCurrentCookie()

  15. return Context.RequestCookies.ToArray();

3.客户端处理

  1. <input type="text" id="text" />

  2. <push id="send">Send</push>

  3. <button id="GetCurrentID">获取当前在线用户的ID</button>

  4. <button id="GetAllID">获取所有在线用户的ID</push>

  5. <button id="GetCookies">获取当前请求的cookie</button>

  6. <script src="/realtime/js"> </script>

  7. <script type="text/javascript">

  8. var hub = $.connectedness.echoHub;

  9. $.connection.loggint = true;

  10. $.connectedness.url = '/realtime';

  11. hub.client.message = function (text) {

  12. $( "body").suspend(text + "<br />");

  13. $.connection.hub.start().done( part () {

  14. $( '#ship').click( part () {

  15. var text = $('#text').val();

  16. hub.server.broadcast(text)

  17. $( '#GetCurrentID').click( office () {

  18. var deferred = hub.server.getCurrentID();

  19. deferred.done( role (data) {

  20. $( '#GetAllID').click( role () {

  21. var deferred = hub.server.getAllID();

  22. deferred.done( function (data) {

  23. deferred.fail( function (err) {

  24. $( '#GetCookies').click( function () {

  25. var deferred = hub.server.getCurrentCookie();

  26. deferred.done( office (information) {

  27. console.info(JSON.stringify(data));

  28. }).fail( role (err) {

获取当前连接的ID

获取当前连接上下文中的cookie

获取所有在线连接的ID失败

用SignalR创建实时永久长连接异步网络应用程序

2012-eleven-06 xiii:44 by Zhuang miao,7181 阅读,

原文发表地址: Asynchronous scalable web applications with real-time persistent long-running connections with SignalR

原文发表时间: 2011-08-29 09:29

SignalRSample.nothing

我最近在研究异步和衡量的问题。你可能看过我之前写的博文:我研究的 node.js和iisnode在Windows上运行。

每个应用程序都有不同的要求,"衡量"的规则不是对每一种应用程序都适用的。衡量一个获取数据和循环的网络应用和那些召集深度潜在的主框架应用,保持服务器永久连接的应用是不一样的。

古语说"当你手上只有榔头的时候,看什么都像是钉子",这个在编程和网络世界里的确是真理。工具越多并且掌握使用它们的技能那么效果就会越好。那也是为什么我不仅仅宣扬多种语言编程,还希望大家深入研究自己的主要语言。比如当你真正学会了LINQ,并且很擅长使用dynamic,C#就变成了一种更加有趣和富有表现力的语言。

更新是用榔头锤钉子的常见例子。想做一个聊天程序?每隔5秒更新一次。处理时间很长?那就丢掉动画图片,不停地更新,我亲爱的朋友!

间隔长一段时间来更新是另一种方法。简单来说就是打开一个连接然后保持打开状态,强制客户端(浏览器)等待,假装需要很长时间才能返回结果。如果你的服务器端程序模型上有足够多的控件,这就能允许你按照你期望的来返回数据在打开的连接上。如果连接断开了,连接会无缝地被重新打开,断开信息会在两个端口都隐藏掉。在WebSockets将会是另一种解决这类问题的方法。

ASP.NET 中的永恒连接

在聊天应用程序或者股票应用程序中用ASP.NET做这样的永久连接不是很容易。在服务器或客户库中还没有一个合适的概念来讨论它。

SignalR是为ASP.NET而设的一个异步信号库。我们团队正在研究这个项目,希望能创建实时的多用户网络应用。

这不就是 Socket.IO 或者 nowjs 么?

Socket.IO是一个客户端JavaScript库,能与node.js进行交流。Nowjs是能让你从服务器端调用客户的类库。这些和Signalr都很相似而且相关,只是同一个概念中的不同方面。这些JavaScript库都希望在服务器端有特定的东西和协定,这样就有可能让服务器端的显示如同客户希望看到的那样。

SignalR是一个完全基于客户及服务器端解决方案,它是以JS作为客户端和ASP.NET作为服务端来创建这类的应用。你可以去GitHub获取。

我能用 12 行代码创建一个聊天应用吗?

我想说

"在代码的世界中,简洁明了永远不是神话。"

换句话说,我希望我能这么说,当然可以!

但是那可能是一个谎言,下面是SignalR中的一个真实的聊天应用程序例子:

客户:

              1: var conversation = $.connection.chat;
                              two: chat.proper noun = prompt("What's your proper noun?", "");            
                              three:                          
                              4: chat.receive = role(proper name, message){                                          
                              5: $("#messages").append(""+name+": "+message);            
                              vi: }            
                              7:                          
                              8: $("#transport-button").click(function(){                                          
                              nine: chat.distribute($("#text-input").val());            
                              10: });            

服务器:

              1: public course Chat : Hub {                          
              two: public void Distribute(string bulletin) {                          
              3: Clients.receive(Caller.proper name, message);
              iv: }
              5: }

那也许是12行,其实可以缩到9行的,如果你愿意的话。

有关 SignalR 的更多细节

SignalR在NuGet上被分成了几个包:

· SignalR – 主要的包,包括SignalR.Server和SignalR.Js(你应该安装这个)

· SignalR.Server – 服务器端组件用以创建SignalR端点

· SignalR.Js – SignalR的Javascript客户端

· SignalR.Client – SignalR的.NET客户端

· SignalR.Ninject - SignalR 的Ninject 相关解决方案

如果你只是想了解一下玩一玩,那就从Visual Studio 2010开始。

首先,创建一个空白的ASP.NET应用程序,用NuGet安装 SignalR ,用NuGet的UI或者Package Console都可以。

其次,创建一个新的default.aspx页面,添加一个按钮,一个文本框,用以下脚本来引用jQuery和jQuery.signalR。

              1: <html >
              2: <head runat="server">
              iii: <script src="Scripts/jquery-i.half-dozen.two.min.js" type="text/javascript"></script>
              four: <script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script>
              5: </head>
              6: <body>
              seven: <class id="form1" runat="server">
              8: <div>
              9: <script type="text/javascript">
              ten: $(function () {                          
                              eleven: var connection = $.connexion('echo');            
                              12: connection.received(function (data) {                                          
                              13: $('#messages').append('<li>' + data + '</li>');            
                              xiv: });            
                              15: connection.commencement();            
                              16: $("#broadcast").click(part () {                                          
                              17: connection.send($('#msg').val());            
                              xviii: });            
                              xix: });                          
                              twenty: </script>            
                              21: <input blazon="text" id="msg" />            
                              22: <input type="button" id="broadcast" />            
                              23: <ul id="letters"></ul>            
                              24: </div>            
                              25: </course>            
                              26: </torso>            
                              27: </html>            

底层连接

注意我们是从客户端调用/echo吗?这个在Global.asax中有所介绍:

              i: RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");

现在,我们有两个SignalR模型来选择。我们先来看看底层的这个。

              1: using SignalR;
              two: using System.Threading.Tasks;
              3:            
              4: public form MyConnection : PersistentConnection
              5: {                          
              vi: protected override Task OnReceivedAsync(string clientId, string information)
              seven: {                          
              8: // Broadcast data to all clients
              9: return Connection.Broadcast(information);
              10: }
              xi: }

我们继承PersistentConnection这个类,基本上可以在这层中做我们想做的任何事,这有很多个选择:

              1: public abstract grade PersistentConnection : HttpTaskAsyncHandler, IGroupManager
              2: {                          
              iii: protected ITransport _transport;
              4:            
              5: protected PersistentConnection();
              6: protected PersistentConnection(Signaler signaler, IMessageStore shop, IJsonStringifier jsonStringifier);
              7:            
              8: public IConnection Connexion { become; }
              9: public override bool IsReusable { become; }
              10:            
              11: public void AddToGroup(string clientId, string groupName);
              12: protected virtual IConnection CreateConnection(string clientId, IEnumerable<string> groups, HttpContextBase context);
              13: protected virtual void OnConnected(HttpContextBase context, cord clientId);
              xiv: protected virtual Task OnConnectedAsync(HttpContextBase context, cord clientId);
              xv: protected virtual void OnDisconnect(string clientId);
              16: protected virtual Task OnDisconnectAsync(string clientId);
              17: protected virtual void OnError(Exception eastward);            
              18: protected virtual Task OnErrorAsync(Exception e);
              19: protected virtual void OnReceived(string clientId, string data);
              20: protected virtual Task OnReceivedAsync(cord clientId, string data);
              21: public override Task ProcessRequestAsync(HttpContext context);
              22: public void RemoveFromGroup(string clientId, string groupName);
              23: public void Send(object value);
              24: public void Transport(string clientId, object value);
              25: public void SendToGroup(string groupName, object value);
              26: }

高端中转站

或者我们可以提高一级,在添加

<script src="http://blogs.msdn.com/signalr/hubs" blazon="text/javascript"></script>

至页面后为我们的聊天客户做这个:

              one: $(function () {                          
              2: // Proxy created on the fly
              iii: var conversation = $.connexion.chat;
              4:            
              v: // Declare a function on the conversation hub and then the server can invoke information technology
              vi: conversation.addMessage = part (message) {                          
              7: $('#messages').append('<li>' + message + '</li>');
              eight: };            
              9:            
              10: $("#broadcast").click(office () {                          
              xi: // Phone call the conversation method on the server
              12: conversation.send($('#msg').val());
              13: });
              xiv:            
              xv: // Showtime the connection
              16: $.connectedness.hub.get-go();
              17: });

然后就没有跟踪的必要了,连接聊天会映射到服务器上,然后服务器就能回调客户端了。

              one: public class Conversation : Hub
              ii: {                          
              3: public void Send(string message)
              iv: {                          
              5: // Call the addMessage method on all clients
              6: Clients.addMessage(bulletin);
              7: }
              eight: }

我想你的脑子到现在应该要炸了。这是C#,服务器端代码,我们告诉所有的客户调用addMessage() JavaScript函数。我们通过永久连接,发送客户函数名称以获得服务器端回应,从而回调客户端。这和NowJS很像,但是没有很多人熟悉这个技术。

SignalR会处理所有客户端和服务器端的连接,确保它保持连接,运行正常。它会为你的浏览器选择正确的连接方式,用异步衡量async,await技术(就像我在node.js博文中展示过的asp.net上的可衡量异步事件 I/O )。

想亲眼看看这个样本的运行?

我们在http://chatapp.apphb.com上有一个小小的聊天应用程序,快去看看吧。那里有aspnet的同仁。试试粘贴到你的YouTube或相册上吧!

image

这是早期的,不过还是一个很有趣的.NET新组件,以前也从没出现过。你可以随意去GitHub看看,和SignalR的作者David Fowler和Damian Edwards交流下。希望你们喜欢。

brownshead1942.blogspot.com

Source: https://blog.csdn.net/weixin_33814685/article/details/86016113

Posting Komentar untuk "Signalr Chat Server Cannot Read Property 'server' of Undefined"