将JS安全websocket连接到C#websocket服务器(Fleck)

时间:2019-05-28 19:25:45

标签: javascript c# asp.net asp.net-core websocket

我在C#(asp.net)中有一个API,其中使用fleck运行此websocket服务器:

SocketService.start();

            SocketService.server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    SocketService.Connessione(socket);
                };
                socket.OnClose = () =>
                {
                    SocketService.Disconnesione(socket);
                };
                socket.OnMessage = message =>
                {
                    SocketService.Messaggio(message, socket);
                };
            });

这是SocketService.Start():

public static void start()
    {
        server = new WebSocketServer($"wss://{GetLocalIPAddress()}:{"4450"}/BNS/");
    }

我已经尝试过使用不安全的ws创建一个简单的HTML / JS页面,并且效果很好。

然后我在主程序中尝试过,我需要它在HTTPS上运行,因此当使用不安全的ws chrome时,我告诉我使用wss。

所以我将ws服务器更改为wss,但随后却什么也不做,这给了我超时错误。

这是JS代码:

var start = function () {
        var wsImpl = window.WebSocket || window.MozWebSocket;
        var form = document.getElementById('sendForm');
        var input = document.getElementById('sendText');

        alert("Connessione...");

        // create a new websocket and connect
        window.ws = new wsImpl('@Percorsi.IndirizzoSocket');

        alert("conn");

        // when the connection is established, this method is called
            ws.onopen = function () {
                alert("Connessione aperta");
                 var openJson = {
                    "Id": "@Model.accountCorrente.Id",
                    "type": "Identificazione"
                 };

                alert("send");
                ws.send(stringify(openJson));
            };
            // when the connection is closed, this method is called
            ws.onclose = function () {
                alert("Connessione chiusa");
            }
            // when data is comming from the server, this metod is called
            ws.onmessage = function (val) {
                if (confirm("Hai ricevuto un nuovo messaggio!\nPremi ok per visualizzarlo.")) {
                    window.location("/Annunci/Chat/" + val);
                } else { }
            };

    }

我不知道如何使它工作。

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

似乎您没有将服务器证书设置为在WS over TLS下使用(不要与HTTPS混淆,HTTPS是TLS上的HTTP)。 如果您在fleck的webpage中看到了该示例,您将意识到必须设置证书:

server.Certificate = new X509Certificate2("MyCert.pfx");