2017-08-29 73 views
0

我試圖建立一個coss域連接。在我的JavaScript客戶端中,我發現連接沒有問題,但是如果我從集線器發送信號,那麼javascript方法不會受到影響。在控制檯中沒有顯示錯誤。 JavaScript變量「聊天」已定義。我查看了互聯網上的嚴重教程,我主要複製了代碼,但它不起作用。SignalR跨域控制檯JavaScript客戶端問題的應用主機

控制檯應用程序主機:

class Program 
    { 
     static void Main(string[] args) 
     { 
      string url = "http://localhost:43253/"; 
      using (WebApp.Start(url)) 
      { 
       Console.WriteLine($"Server running on {url}"); 
       Console.ReadKey(); 
       MyHub hub = new MyHub(); 
       hub.Send("test", "test"); 
       Console.ReadKey(); 
      } 
     } 
    } 

    class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      app.Map("/signalr", map => 
      { 
       // Setup the cors middleware to run before SignalR. 
       // By default this will allow all origins. You can 
       // configure the set of origins and/or http verbs by 
       // providing a cors options with a different policy. 
       map.UseCors(CorsOptions.AllowAll); 

       var hubConfiguration = new HubConfiguration 
       { 

       }; 

       // Run the SignalR pipeline. We're not using MapSignalR 
       // since this branch is already runs under the "/signalr" 
       // path. 
       map.RunSignalR(hubConfiguration); 
      }); 
     } 
    } 

    public class MyHub : Hub 
    { 
     public override Task OnConnected() 
     { 
      Console.WriteLine("connected"); 
      return base.OnConnected(); 
     } 

     public void Send(string name, string message) 
     { 
      var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); 
      context.Clients.All.addMessage(name, message); 
     } 
    } 

JavaScript客戶端:

@{ 
    Layout = null; 
} 

<!DOCTYPE html> 

<html> 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>Index</title> 

</head> 
<body> 
    <div id="image"> 
    </div> 
    <script src="~/Scripts/jquery-1.6.4.min.js"></script> 
    <script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script> 
    <script src="http://localhost:43253/signalr/hubs"></script> 
    <script type="text/javascript"> 
     $(function() { 
      $.connection.hub.url = "http://localhost:43253/signalr"; 
      var chat = $.connection.myHub; 

      chat.client.addMessage = function (name, message) { 
       console.log(name + message); 
      } 
     }); 
    </script> 
</body> 
</html> 

回答

0

我固定它。問題是我忘了開始連接。剛剛添加:$ .connection.hub.start();在JavaScript客戶端的末尾