雪花

三、Signalr外部链接

一、本地外部引用

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    <script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.js"></script>
    <script src="http://localhost:52992/lib/signalr/dist/browser/signalr.js"></script>
    <script type="text/javascript">
        "use strict";
        $(function () {

          var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:52992/chatHub").build();
            // var connection = $.connection('http://localhost:8000/signalr');
            // connection
            connection.start().then(function () {
                console.log("链接成功!");
            }).catch(function (err) {
                return console.error(err.toString());
            });
            //接受消息
            connection.on("ReceiveMessage", function (message) {
                console.log(message);
                var obj = JSON.stringify(message);
                console.log(obj);
                //var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                //var encodedMsg = msg;
                //var li = document.createElement("li");
                //li.textContent = encodedMsg;
                //document.getElementById("messagesList").appendChild(li);
            });
            $("#sendmessage").click(function() {
                //发送消息
                var msgObj = {
                    "Type": 1,
                    "LoginUserId": 3100003640,
                    "UserName": "孙凤才",
                    "GroupId": 1,
                    "Content": "消息发送成功",
                    "RecordId": 140,
                    "Index": 137,
                };
                connection.invoke("SendMessage", "sdad",JSON.stringify(msgObj)).catch(function (err) {
                    return console.error(err.toString());
                });
            });
        });
    </script>
</body>
</html>

后面几点要注意:

 

解决方式:

 

app.UseCors(builder =>
{
    builder.SetIsOriginAllowed(origin => true)
        .AllowAnyHeader()
        .WithMethods("GET", "POST")
        .AllowCredentials();
});

即最终是

 

posted @ 2019-11-07 10:22  十色  阅读(331)  评论(0编辑  收藏  举报