CrazyIter_Bin 4 months ago
parent
commit
f316b19d1d

+ 103 - 0
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/ClientApp/public/signalr.html

@@ -0,0 +1,103 @@
+<!DOCTYPE html>
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+    <meta charset="utf-8" />
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.7/signalr.min.js"></script>
+    <title></title>
+    <style type="text/css">
+        .content {
+            width: 100%;
+            height: 100%;
+            display: flex;
+            justify-content: left;
+            border: solid #4cff00 1px;
+            margin-top: 2rem;
+        }
+
+        .badge {
+            font-size: large;
+            font-weight: bolder;
+            color: aquamarine;
+        }
+
+        #messagesList {
+            width: 100%;
+        }
+    </style>
+</head>
+<body>
+
+    <div class="container">
+        <textarea rows="3" id="text" cols="120" class="text" placeholder="输入要发送的文字信息"></textarea>
+        <button id="send" class="btn btn-primary">发送</button>
+        <div class="content">
+            <ul id="messagesList" class="list-group">
+            </ul>
+        </div>
+    </div>
+    <script>
+        window.onload = function () {
+            const clientid = this.prompt('请输clientid')
+            const data = {
+                clientid: clientid,
+                grant_type: 'check_file'
+            }
+            if (data.clientid) {
+                const url = `/signalr/exam?grant_type=${data.grant_type}&clientid=dedbdcf5545c6f83093883a63142687d-127.0.0.1`
+                const connection = new signalR.HubConnectionBuilder()
+                    .withUrl(url)
+                    .configureLogging(signalR.LogLevel.Information)
+                    .build();
+                connection.start().then(function () {
+                    console.log(`${data.clientid}连接成功......`);
+                    //appendContent(`${data.scene}连接成功......`);
+                });
+                connection.on("ReceiveConnection", (message) => {
+                    console.log('ReceiveConnection-MESSAGE', message);
+                    appendContent(message.content);
+                });
+                connection.on("ReceiveMessage", (message) => {
+                    console.log('ReceiveMessage-MESSAGE', message);
+                    appendContent(message.content, message.clientid);
+                });
+                const btn = document.getElementById("send")
+                btn.addEventListener('click', function () {
+                    const target = document.getElementById('text')
+                    connection.invoke("ReceiveMessage", data.clientid, data.grant_type,target.value)
+                        .then(_ => {
+                            target.value = '';
+                        })
+                        .catch(err => console.error(err.toString()));
+                })
+            }
+        }
+        function appendContent(content, badge) {
+            let li = document.createElement("li");
+            li.className = 'list-group-item';
+            if (badge) {
+                const span = document.createElement('span');
+                span.className = 'badge';
+                span.innerText = badge + ':';
+                li.appendChild(span);
+            }
+            li.innerHTML += content;
+            document.getElementById("messagesList").appendChild(li);
+        }
+
+        //async function start() {
+        //    try {
+        //        await connection.start();
+        //        console.log("已经连接 SignalR Connected.");
+        //    } catch (err) {
+        //        console.log(err);
+        //        setTimeout(start, 5000);
+        //    }
+        //};
+        //connection.onclose(async () => {
+        //    await start();
+        //});
+        //start();
+    </script>
+</body>
+</html>

+ 5 - 52
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/DI/SignalRHost/SignalRExamServerHub.cs

@@ -83,58 +83,11 @@ namespace IES.ExamServer.DI.SignalRHost
         /// <param name="message"></param>
         /// <returns></returns>
 
-        public async Task SendMessage(string clientId, string grant_type, MessageContent content )
+        public  void ReceiveMessage(string clientId, string grant_type, string contentmsg )
         {
-            //双向检测是否连接。
-            SignalRClient signalRClient = _memoryCache.Get<SignalRClient>($"{Constant._KeySignalRClientClients}:{clientId}");
-            if (signalRClient!=null)
-            {
-                signalRClient = _memoryCache.Get<SignalRClient>($"{Constant._KeySignalRClientConnects}:{signalRClient.connid}");
-            }
-            int code=0;
-            string msg = "";
-            CheckFileMessageBody messageBody = new CheckFileMessageBody
-            {
-                content = content.content,
-                status = content.status,
-                clientid = clientId,
-                connid = signalRClient?.connid,
-                grant_type = grant_type,
-                time = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
-                type = Constant._Message_type_message,
-                contents = content.contents
-            };
-            if (signalRClient != null)
-            {
-
-                try
-                {
-                    switch (true)
-                    {
-                        case bool when grant_type.Equals(Constant._Message_grant_type_check_file):
-                            {
-                                await Clients.Client(signalRClient.connid!).ReceiveMessage(messageBody);
-                                code=200;
-                                msg = $"发送成功";
-                                break;
-                            }
-                        default:
-                            break;
-                    }
-                }
-                catch (Exception ex)
-                {
-                    code=500;
-                    msg = $"{ex.Message},{ex.StackTrace}";
-                }
-            }
-            else {
-                code= 400;
-                msg="未连接客户端";
-            }
-            _logger.LogData<object>(new {code ,msg,data =  messageBody }, content.dataId!);
+            _logger.LogInformation($"收到客户端的消息{contentmsg}");
         }
-
+   
         /// <summary>
         /// 客户连接成功时触发
         /// </summary>
@@ -166,8 +119,8 @@ namespace IES.ExamServer.DI.SignalRHost
                         // 检查文件
                         case bool when grant_type.Equals(Constant._Message_grant_type_check_file):
                             {
-                                _memoryCache.Set($"{Constant._KeySignalRClientClients}:{Constant._Message_grant_type_check_file}:{clientid}", client);
-                                _memoryCache.Set($"{Constant._KeySignalRClientConnects}:{Constant._Message_grant_type_check_file}:{connid}", client);
+                                _memoryCache.Set($"{Constant._KeySignalRClientClients}:{clientid}", client);
+                                _memoryCache.Set($"{Constant._KeySignalRClientConnects}:{connid}", client);
                                 await SendConnection(connid, new ConnectionMessageBody
                                 {
                                     connid=connid,

+ 15 - 7
TEAMModelOS.Extension/IES.Exam/IES.ExamServer/Program.cs

@@ -91,14 +91,22 @@ namespace IES.ExamServer
             builder.Services.AddSingleton<ServiceInitializer>();
             builder.Services.AddCors(options =>
             {
-                options.AddDefaultPolicy(
-                builder =>
+                //options.AddDefaultPolicy(
+                //builder =>
+                //{
+
+                //    builder.AllowAnyOrigin()
+                //            .AllowAnyHeader()
+                //            .AllowAnyMethod();
+                //});
+                options.AddPolicy("any", builder =>
                 {
-
-                    builder.AllowAnyOrigin()
-                            .AllowAnyHeader()
-                            .AllowAnyMethod();
+                    builder.SetIsOriginAllowed(x=>true)
+                    .AllowAnyMethod()
+                    .AllowAnyHeader()
+                    .AllowCredentials();
                 });
+
             });
             builder.Services.AddMvcFilter<AuthTokenActionFilter>();
             // 添加自定义日志提供程序
@@ -148,7 +156,7 @@ namespace IES.ExamServer
             app.UseStaticFiles();
 
             app.UseRouting();
-
+            app.UseCors("any");
             app.UseAuthorization();
 
             app.MapHub<SignalRExamServerHub>("/signalr/exam").RequireCors("any");