信号器与asp.net Windows服务

时间:2017-12-12 06:57:51

标签: asp.net windows-services signalr

我创建了Windows服务并执行该exe服务器。 我的Windows服务代码是

public partial class Service1 : ServiceBase
 {
    private Timer timer1 = null;
    public Service1()
    {
       // System.Diagnostics.Debugger.Launch();
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        timer1 = new Timer();
        this.timer1.Interval = 30000;
        this.timer1.Elapsed += new 
        System.Timers.ElapsedEventHandler(this.timer1_tick);
        timer1.Enabled = true;
        Test_Library.writelog("Start");
    }
    private void timer1_tick(object sender,EventArgs e)
    {
        Test_Library.writelog("Time-Ticker Started at "+ DateTime.Now);
        string url = "https://localhost:8080/";
        try
        {
             Test_Library.writelog("Call Startup Class at "+ DateTime.Now);
             WebApp.Start<Startup>(url);
            Test_Library.writelog("End  Startup Class at "+ DateTime.Now);
        }
        catch( TargetInvocationException  ex)
        { 
            Test_Library.writelog("Error in  Startup Class at "+ DateTime.Now+ " Exception is : " +ex);
            return;
        }


    }

    protected override void OnStop()
    {
        timer1.Enabled = false;
        Test_Library.writelog("Stop at " + DateTime.Now);
    }
}

public class Startup
{
    public void Configuration(IAppBuilder app)
    {

        try
        {

            //Test_Library.writelog("SignalR Configuartion Started at "+ DateTime.Now);
            //var hubConfiguration = new HubConfiguration
            //{
            //    EnableJSONP = true,
            //    EnableDetailedErrors = true

            //};
            //app.MapSignalR(hubConfiguration);
            app.Map("/Signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP = true,
                    EnableDetailedErrors = true

                };
                map.RunSignalR(hubConfiguration);                
            });
        }
        catch (Exception ex)
        {
            Test_Library.writelog("SignalR Error at " + DateTime.Now + " " + ex.ToString());
            //var writer = new StreamWriter("ClientLog.txt");
            //writer.AutoFlush = true;
            //hubConnection.TraceLevel = TraceLevels.All;
            //hubConnection.TraceWriter = writer;
        }
    }
}

public class MyHub : Hub
{
    public void Send(string name, string message)
    {
        Clients.All.broadcastMessage(name, message);
    }
    public override Task OnConnected()
    {
        Test_Library.writelog("SignalR Client connected: "  + DateTime.Now + " " + Context.ConnectionId);
       // Program.mainForm.WriteToConsole("Client connected: " + Context.ConnectionId);
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool tr)
    {
        Test_Library.writelog("SignalR Client disconnected: " + DateTime.Now + " " + Context.ConnectionId);
      //  Program.mainForm.WriteToConsole("Client disconnected: " + Context.ConnectionId);
        return base.OnDisconnected(true);
    }
}

我的客户端代码是[生成代理。 (Server.js)]

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Signalr Simple Chat</title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.2.2.min.js"></script>  
    <script src="Scripts/server.js"></script>
    <script type="text/javascript">

            //Generated proxy

        $(function () {
            var connection = $.hubConnection('/signalr/', { useDefaultPath: false });
            connection.url = "https://localhost:8080/signalr";
            connection.logging = true;
            connection.connected = true;
            var chat = connection.createHubProxy('myHub');
            chat.on('broadcastMessage', function (name, message) {
                var encodename = $('<div/>').text(name).html();
                var encodemsg = $('<div/>').text(message).html();
                $('#discussion').append('<li><strong>' + encodename + '</strong>: &nbsp;&nbsp;' + encodemsg + '</li>');
            });

            $('#displayname').val(prompt('Enter your name:', ''));
            $('#message').focus();

            try {
                connection.start({ transport: ['webSockets', 'longPolling'], jsonp: true }).done(function () {
                    $('#btnsendmsg').click(function () {
                        console.log('Now connected, connection ID=' + connection.id);
                        chat.invoke('send', $('#displayname').val(), $(message).val());
                    });
                }).fail(function () {
                    window.onerror = function () {
                        console.log('Could not connect connection failed');
                    };

                });
            }
            catch (ex) {
                console.log('Error=' + ex);
            }
            finally {
                console.log('Final block ');
            }

        });

    </script>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="btnsendmsg" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>



</body>
</html>

当我执行Windows服务并启动服务时,我将运行客户端应用程序,我得到的错误是&#34; https://localhost:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22myhub%22%7D%5D&callback=jQuery16406560848134472517_1513061441115&_=1513061443867&#34;。

如何解决这个问题。请告诉我。

提前致谢..

通过 Angappan.S

1 个答案:

答案 0 :(得分:0)

您是否尝试删除EnableJSONP;

            var hubConfiguration = new HubConfiguration
            {
                EnableDetailedErrors = true
            };

和客户端;

connection.start({ transport: ['webSockets', 'longPolling'] })