From 35a0710ab5bb032acd945960386c31e7777e9323 Mon Sep 17 00:00:00 2001 From: zerlei <1445089819@qq.com> Date: Fri, 11 Oct 2024 09:04:58 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20websocket=20pipeline=20=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E4=BF=AE=E5=A4=8D=E4=BA=86=E5=A4=A7=E9=87=8F=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98=EF=BC=8C=E4=B8=80=E5=A4=A7=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=98=AF=E5=AF=B9websocket=E5=92=8Cc#=20=E4=B8=8D=E7=86=9F?= =?UTF-8?q?=E6=82=89=E6=89=80=E8=87=B4=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 上传文件bug修复 - 继续测试修改bug - 代码审查处理,添加必要注释,风格规范性等 --- Server/Common/AES.cs | 2 +- Server/Common/ConnectPipeline.cs | 97 ++++++++++++------- Server/Common/Message.cs | 3 +- .../Controllers/LocalServerController.cs | 2 +- Server/LocalServer/StateHelper.cs | 5 +- Server/LocalServer/appsettings.json | 2 +- .../Controllers/RemoteServerController.cs | 7 +- Server/RemoteServer/Program.cs | 7 ++ Server/RemoteServer/appsettings.json | 8 +- Tool/webtool/src/App.vue | 43 ++++++-- Tool/webtool/src/connect.js | 41 +++++--- 11 files changed, 148 insertions(+), 69 deletions(-) diff --git a/Server/Common/AES.cs b/Server/Common/AES.cs index ac3cc13..0ec881c 100644 --- a/Server/Common/AES.cs +++ b/Server/Common/AES.cs @@ -120,7 +120,7 @@ public class AESHelper // Declare the string used to hold // the decrypted text. - string plaintext = null; + string plaintext = string.Empty; // Create an Aes object // with the specified key and IV. diff --git a/Server/Common/ConnectPipeline.cs b/Server/Common/ConnectPipeline.cs index 49b4578..144c0a2 100644 --- a/Server/Common/ConnectPipeline.cs +++ b/Server/Common/ConnectPipeline.cs @@ -27,7 +27,7 @@ public abstract class AbsPipeLine(bool isAES) /// public abstract Task SendMsg(SyncMsg msg); - public abstract Task UploadFile(string filePath, string url, Func progressCb); + public abstract Task UploadFile(string url, string filePath, Func progressCb); protected readonly bool IsAES = isAES; } @@ -37,33 +37,27 @@ public class WebSocPipeLine(TSocket socket, bool isAES) : AbsPipeLine(i public readonly TSocket Socket = socket; public override async Task UploadFile( - string filePath, string url, + string filePath, Func progressCb ) { - if (Socket is HttpClient) - { - using var client = new HttpClient(); - using var content = new MultipartFormDataContent(); - using var fileStream = new FileStream(filePath, FileMode.Open); - var progress = new Progress( - (current) => - { - progressCb(current); - } - ); - var fileContent = new ProgressStreamContent(fileStream, progress); - content.Add(fileContent, "file", Path.GetFileName(filePath)); - var it = await client.PostAsync("http://" + url + "/UploadPacked", content); - if (it.StatusCode != System.Net.HttpStatusCode.OK) + //throw new Exception("sdfsdf"); + using var client = new HttpClient(); + using var content = new MultipartFormDataContent(); + using var fileStream = new FileStream(filePath, FileMode.Open); + var progress = new Progress( + (current) => { - throw new Exception(it.Content.ReadAsStringAsync().Result); + progressCb(current); } - } - else + ); + //var fileContent = new ProgressStreamContent(fileStream, progress); + content.Add(new StreamContent(fileStream), "file", Path.GetFileName(filePath)); + var it = await client.PostAsync("http://" + url + "/UploadFile", content); + if (it.StatusCode != System.Net.HttpStatusCode.OK) { - throw new NotSupportedException("只支持HttpClient!"); + throw new Exception(it.Content.ReadAsStringAsync().Result); } } @@ -106,7 +100,9 @@ public class WebSocPipeLine(TSocket socket, bool isAES) : AbsPipeLine(i System.Buffer.BlockCopy(buffer, 0, nbuffer, 0, receiveResult.Count); if (IsAES) { - var nnbuffer = AESHelper.DecryptStringFromBytes_Aes(buffer); + //var msg1 = Encoding.UTF8.GetString(nbuffer); + //var n1Buffler = Encoding.UTF8.GetBytes(msg1); + var nnbuffer = AESHelper.DecryptStringFromBytes_Aes(nbuffer); receiveCb(Encoding.UTF8.GetBytes(nnbuffer)); } else @@ -129,24 +125,55 @@ public class WebSocPipeLine(TSocket socket, bool isAES) : AbsPipeLine(i // Body = CloseReason ?? "" // } //); - await Socket.CloseAsync( - WebSocketCloseStatus.NormalClosure, - CloseReason, - CancellationToken.None - ); + if (Encoding.UTF8.GetBytes(CloseReason ?? "").Length > 120) + { + await SendMsg( + new SyncMsg + { + Type = SyncMsgType.Error, + Step = SyncProcessStep.CloseError, + Body = CloseReason ?? "" + } + ); + await Socket.CloseAsync( + WebSocketCloseStatus.NormalClosure, + "查看上一条错误信息!", + CancellationToken.None + ); + } + else + { + await Socket.CloseAsync( + WebSocketCloseStatus.NormalClosure, + CloseReason, + CancellationToken.None + ); + } } } public override async Task SendMsg(SyncMsg msg) { string msgStr = JsonSerializer.Serialize(msg); - await Socket.SendAsync( - IsAES - ? AESHelper.EncryptStringToBytes_Aes(msgStr) - : new ArraySegment(Encoding.UTF8.GetBytes(msgStr)), - WebSocketMessageType.Text, - true, - CancellationToken.None - ); + var it = AESHelper.EncryptStringToBytes_Aes(msgStr); + //var xx = new ArraySegment(it); + if (IsAES) + { + await Socket.SendAsync( + new ArraySegment(it), + WebSocketMessageType.Binary, + true, + CancellationToken.None + ); + } + else + { + await Socket.SendAsync( + new ArraySegment(Encoding.UTF8.GetBytes(msgStr)), + WebSocketMessageType.Text, + true, + CancellationToken.None + ); + } } } diff --git a/Server/Common/Message.cs b/Server/Common/Message.cs index 23a67cf..a7f9b9a 100644 --- a/Server/Common/Message.cs +++ b/Server/Common/Message.cs @@ -15,7 +15,8 @@ public enum SyncProcessStep DiffFileAndPack = 3, PackSqlServer = 4, UploadAndUnpack = 5, - Publish = 6 + Publish = 6, + CloseError = 7 } public class SyncMsg diff --git a/Server/LocalServer/Controllers/LocalServerController.cs b/Server/LocalServer/Controllers/LocalServerController.cs index d85810f..19fee47 100644 --- a/Server/LocalServer/Controllers/LocalServerController.cs +++ b/Server/LocalServer/Controllers/LocalServerController.cs @@ -55,7 +55,7 @@ namespace LocalServer.Controllers await Factory.CreateLocalSyncServer( pipeLine, Name, - new WebSocPipeLine(new ClientWebSocket(), false) + new WebSocPipeLine(new ClientWebSocket(), true) ); } else diff --git a/Server/LocalServer/StateHelper.cs b/Server/LocalServer/StateHelper.cs index 325fcc9..01a617e 100644 --- a/Server/LocalServer/StateHelper.cs +++ b/Server/LocalServer/StateHelper.cs @@ -124,7 +124,7 @@ public class ConnectAuthorityHelper(LocalSyncServer context) } catch (Exception e) { - await Context.LocalPipe.Close(e.Message); + Context.Close(e.Message); } }); } @@ -301,6 +301,7 @@ public class DiffFileAndPackHelper(LocalSyncServer context) e.DiffDirInfo.WriteByThisInfo(PackOp); } }); + Context.LocalPipe.SendMsg(CreateMsg("文件差异比较成功!")).Wait(); var n = new DeployMSSqlHelper(Context); Context.SetStateHelper(n); n.PackSqlServerProcess(); @@ -414,8 +415,6 @@ public class UploadPackedHelper(LocalSyncServer context) ) .Wait(); Context.LocalPipe.SendMsg(CreateMsg("上传完成!")).Wait(); - - var x = Context.GetStateHelper().Step; } protected override void HandleLocalMsg(SyncMsg msg) diff --git a/Server/LocalServer/appsettings.json b/Server/LocalServer/appsettings.json index d8da422..4a340ef 100644 --- a/Server/LocalServer/appsettings.json +++ b/Server/LocalServer/appsettings.json @@ -6,7 +6,7 @@ } }, "AllowedHosts": "*", - "TempDir": "D:/TempPack", + "TempDir": "D:\\FileSyncTest\\stemp", "SqlPackageAbPath": "C:\\Users\\ZHAOLEI\\.dotnet\\tools\\sqlpackage.exe", //"MsdeployAbPath": "C:\\Program Files\\IIS\\Microsoft Web Deploy V3\\msdeploy.exe", "MSBuildAbPath": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\MSBuild\\Current\\Bin\\amd64\\MSBuild.exe" diff --git a/Server/RemoteServer/Controllers/RemoteServerController.cs b/Server/RemoteServer/Controllers/RemoteServerController.cs index c6f2b65..d8a447d 100644 --- a/Server/RemoteServer/Controllers/RemoteServerController.cs +++ b/Server/RemoteServer/Controllers/RemoteServerController.cs @@ -24,6 +24,8 @@ public class SyncFilesController(RemoteSyncServerFactory factory, SqliteDbContex var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); var pipeLine = new WebSocPipeLine(webSocket, true); await Factory.CreateRemoteSyncServer(pipeLine, Name); + + var x = 11; } else { @@ -195,10 +197,7 @@ public class SyncFilesController(RemoteSyncServerFactory factory, SqliteDbContex } catch (Exception ex) { - return StatusCode( - 500, - new { IsSuccess = false, Message = $"Internal server error: {ex.Message}" } - ); + return StatusCode(500, new { IsSuccess = false, Message = $"上传文件失败: {ex.Message}" }); } } } diff --git a/Server/RemoteServer/Program.cs b/Server/RemoteServer/Program.cs index 50f5ce1..8e8aeb7 100644 --- a/Server/RemoteServer/Program.cs +++ b/Server/RemoteServer/Program.cs @@ -14,6 +14,13 @@ RemoteSyncServerFactory.NamePwd = [ .. (builder.Configuration.GetSection("NamePwds").Get[]>() ?? []) ]; +foreach (var x in builder.Configuration.GetSection("NamePwds").GetChildren()) +{ + var it = x.GetChildren(); + RemoteSyncServerFactory.NamePwd.Add( + new Tuple(it.ElementAt(0).Value ?? "", it.ElementAt(1).Value ?? "") + ); +} RemoteSyncServer.SqlPackageAbPath = builder.Configuration["SqlPackageAbPath"] ?? "C:\\Users\\ZHAOLEI\\.dotnet\\tools\\sqlpackage.exe"; diff --git a/Server/RemoteServer/appsettings.json b/Server/RemoteServer/appsettings.json index 70b1de0..40f7a82 100644 --- a/Server/RemoteServer/appsettings.json +++ b/Server/RemoteServer/appsettings.json @@ -9,9 +9,9 @@ } }, "AllowedHosts": "*", - "TempDir":"D:/TempPack2", - "NamePwds":[ - ["test","testpwd"] + "TempDir": "D:\\FileSyncTest\\dtemp", + "NamePwds": [ + [ "Test", "t123" ] ], - "SqlPackageAbPath": "C:\\Users\\ZHAOLEI\\.dotnet\\tools\\sqlpackage.exe", + "SqlPackageAbPath": "C:\\Users\\ZHAOLEI\\.dotnet\\tools\\sqlpackage.exe" } diff --git a/Tool/webtool/src/App.vue b/Tool/webtool/src/App.vue index 8d724ff..add3d1d 100644 --- a/Tool/webtool/src/App.vue +++ b/Tool/webtool/src/App.vue @@ -11,6 +11,9 @@ const options = ref({ lineHeight: 24, tabSize: 2, }) + +let Pipe = null +const Msgs = ref([]) const code = ref(` config = { Name: "Test", @@ -51,7 +54,31 @@ config = { ], }; `) +var CStatus = ref('None') +function publishCB(MsgIt) { + + if (MsgIt.Type == 2) { + Msgs.value[Msgs.value.length - 1] = MsgIt + } else { + Msgs.value.push(MsgIt) + } + if (MsgIt.Step == 6) { + if (MsgIt.Body == "发布完成!") { + CStatus.value = 'Success' + Pipe.ClosePipe() + window.alert("正确:发布完成!") + } + } + if (MsgIt.Step == 8) { + if (CStatus.value != "Success") { + window.alert("失败:请查看错误信息!") + } + CStatus.value = "None" + } + +} function submit() { + Msgs.value = [] var config = {} try { eval(code.value) @@ -60,8 +87,9 @@ function submit() { } cacheConfig.value[config.Name] = config updateStorage() - var p = new ConnectPipe() - p.OpenPipe(config,()=>{}) + Pipe = new ConnectPipe() + Pipe.OpenPipe(config, publishCB) + CStatus.value = "Process" } catch (e) { @@ -89,9 +117,6 @@ function updateStorage() { } -function publishCB(MsgIt) { - -} onMounted(() => { var cacheConfigStr = localStorage.getItem('config') if (cacheConfigStr) { @@ -111,11 +136,17 @@ onMounted(() => { v-model:value="code">
发布日志 + +

+ [{{ msg.Step + > 6 ? msg.Step > 7 ? "关闭" : "错误" : `${msg.Step}/${6}`}}] + {{ msg.Body }} +

- + diff --git a/Tool/webtool/src/connect.js b/Tool/webtool/src/connect.js index 31af00a..33c5b96 100644 --- a/Tool/webtool/src/connect.js +++ b/Tool/webtool/src/connect.js @@ -6,30 +6,45 @@ class ConnectPipe { // this.#websocket = new WebSocket(`ws://${window.location.host}`) } OpenPipe(config, MsgCb) { - this.config = config; - // var webSocUrl = `ws://${window.location.host}:${window.location.port}/websoc?Name=${config.Name}` - var webSocUrl = "ws://127.0.0.1:6818/websoc?Name=Test" + var webSocUrl = "ws://127.0.0.1:6818/websoc?Name=Test"; this.#websocket = new WebSocket(webSocUrl); this.#websocket.onopen = (event) => { - // console.warn("websocket connected!"); - this.#websocket.send(JSON.stringify(this.config)); + var starter = { + Body: JSON.stringify(config), + Type: 1, + Step: 1, + }; + // console.warn("websocket connected!"); + this.#websocket.send(JSON.stringify(starter)); }; this.#websocket.onmessage = (event) => { - console.log(event.data) - + // console.log(event.data); + MsgCb(JSON.parse(event.data)) }; this.#websocket.onclose = (event) => { - console.warn(event.reason) + + console.warn(event) + MsgCb({ + Type: 0, + Step: 8, + Body:event.reason + }) + }; this.#websocket.onerror = (e) => { - console.error(e) - if (this.#websocket.readyState) { - //bla bla - } + console.error(e); + MsgCb({ + Type: 0, + Body: "异常错误,查看 Console", + Step: 7, + }); }; } + ClosePipe() { + this.#websocket.close(); + } + } - export default ConnectPipe;