From 5517ea9df8ebf656acb3e59bc52dd6711315dff5 Mon Sep 17 00:00:00 2001 From: zerlei <1445089819@qq.com> Date: Thu, 10 Oct 2024 13:15:14 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20c#=20websocket=20=E4=B8=8D=E8=83=BD?= =?UTF-8?q?=E8=84=B1=E7=A6=BBhttp=E4=B8=8A=E4=B8=8B=E6=96=87=EF=BC=8C?= =?UTF-8?q?=E4=B9=9F=E5=B0=B1=E6=98=AF=E8=AF=B7=E6=B1=82=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E7=9A=84=E5=87=BD=E6=95=B0=E4=BD=9C=E7=94=A8=E5=9F=9F=EF=BC=8C?= =?UTF-8?q?=E5=90=A6=E5=88=99=E5=B0=B1=E4=BC=9A=E5=BC=82=E5=B8=B8=E9=80=80?= =?UTF-8?q?=E5=87=BA=EF=BC=88=E8=BF=99=E6=98=AF=E4=BB=80=E4=B9=88=EF=BC=9F?= =?UTF-8?q?=EF=BC=89=E3=80=82=20=E5=9B=A0=E6=AD=A4=E6=94=B9=E4=BA=86?= =?UTF-8?q?=E4=B8=80=E4=BA=9Bwebsocket=E7=9A=84=E7=BB=93=E6=9E=84=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Server/Common/ConnectPipeline.cs | 12 +++++-- .../Controllers/LocalServerController.cs | 33 ++++++++++++++++++- Server/LocalServer/LocalSyncServer.cs | 32 +++++++++--------- Server/LocalServer/LocalSyncServerFactory.cs | 16 ++++----- .../Controllers/RemoteServerController.cs | 2 +- Server/RemoteServer/Program.cs | 2 +- Server/RemoteServer/RemoteSyncServer.cs | 32 +++++++++--------- .../RemoteServer/RemoteSyncServerFactory.cs | 3 +- Server/ServerTest/PipeTest.cs | 12 +++++-- Tool/webtool/src/App.vue | 14 +++++--- Tool/webtool/src/connect.js | 16 +++++---- 11 files changed, 115 insertions(+), 59 deletions(-) diff --git a/Server/Common/ConnectPipeline.cs b/Server/Common/ConnectPipeline.cs index 5aba076..49b4578 100644 --- a/Server/Common/ConnectPipeline.cs +++ b/Server/Common/ConnectPipeline.cs @@ -55,7 +55,7 @@ public class WebSocPipeLine(TSocket socket, bool isAES) : AbsPipeLine(i ); var fileContent = new ProgressStreamContent(fileStream, progress); content.Add(fileContent, "file", Path.GetFileName(filePath)); - var it = await client.PostAsync(url + "/UploadPacked", content); + var it = await client.PostAsync("http://" + url + "/UploadPacked", content); if (it.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception(it.Content.ReadAsStringAsync().Result); @@ -72,7 +72,7 @@ public class WebSocPipeLine(TSocket socket, bool isAES) : AbsPipeLine(i if (Socket is ClientWebSocket CSocket) { //连接失败会抛出异常 - await CSocket.ConnectAsync(new Uri(addr), CancellationToken.None); + await CSocket.ConnectAsync(new Uri("ws://" + addr), CancellationToken.None); yield return 0; } // 从controller 来,这个已经连接上了 @@ -121,6 +121,14 @@ public class WebSocPipeLine(TSocket socket, bool isAES) : AbsPipeLine(i { if (Socket.State == WebSocketState.Open) { + //await SendMsg( + // new SyncMsg + // { + // Type = SyncMsgType.Error, + // Step = SyncProcessStep.Finally, + // Body = CloseReason ?? "" + // } + //); await Socket.CloseAsync( WebSocketCloseStatus.NormalClosure, CloseReason, diff --git a/Server/LocalServer/Controllers/LocalServerController.cs b/Server/LocalServer/Controllers/LocalServerController.cs index 56fb6e4..d85810f 100644 --- a/Server/LocalServer/Controllers/LocalServerController.cs +++ b/Server/LocalServer/Controllers/LocalServerController.cs @@ -10,6 +10,36 @@ namespace LocalServer.Controllers { private readonly LocalSyncServerFactory Factory = factory; + private static async Task Echo(WebSocket webSocket) + { + var buffer = new byte[1024 * 4]; + var receiveResult = await webSocket.ReceiveAsync( + new ArraySegment(buffer), + CancellationToken.None + ); + + while (!receiveResult.CloseStatus.HasValue) + { + await webSocket.SendAsync( + new ArraySegment(buffer, 0, receiveResult.Count), + receiveResult.MessageType, + receiveResult.EndOfMessage, + CancellationToken.None + ); + + receiveResult = await webSocket.ReceiveAsync( + new ArraySegment(buffer), + CancellationToken.None + ); + } + + await webSocket.CloseAsync( + receiveResult.CloseStatus.Value, + receiveResult.CloseStatusDescription, + CancellationToken.None + ); + } + [Route("/websoc")] public async Task WebsocketConnection(string Name) { @@ -20,8 +50,9 @@ namespace LocalServer.Controllers if (Factory.GetServerByName(Name) == null) { var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); + //await Echo(webSocket); var pipeLine = new WebSocPipeLine(webSocket, false); - Factory.CreateLocalSyncServer( + await Factory.CreateLocalSyncServer( pipeLine, Name, new WebSocPipeLine(new ClientWebSocket(), false) diff --git a/Server/LocalServer/LocalSyncServer.cs b/Server/LocalServer/LocalSyncServer.cs index fecf825..219ce86 100644 --- a/Server/LocalServer/LocalSyncServer.cs +++ b/Server/LocalServer/LocalSyncServer.cs @@ -105,24 +105,24 @@ public class LocalSyncServer StateHelper = new ConnectAuthorityHelper(this); Name = name; RemotePipe = remotePipe; + } - Task.Run(async () => + public async Task Connect() + { + try { - try - { - var rs = LocalPipe.Work( - (byte[] b) => - { - return StateHelper.ReceiveLocalMsg(b); - } - ); - await foreach (var r in rs) { } - } - catch (Exception e) - { - Close(e.Message); - } - }); + var rs = LocalPipe.Work( + (byte[] b) => + { + return StateHelper.ReceiveLocalMsg(b); + } + ); + await foreach (var r in rs) { } + } + catch (Exception e) + { + Close(e.Message); + } } public void Close(string? CloseReason) diff --git a/Server/LocalServer/LocalSyncServerFactory.cs b/Server/LocalServer/LocalSyncServerFactory.cs index 1f6ff41..7e50a2f 100644 --- a/Server/LocalServer/LocalSyncServerFactory.cs +++ b/Server/LocalServer/LocalSyncServerFactory.cs @@ -1,5 +1,5 @@ -using Common; using System.Net.WebSockets; +using Common; namespace LocalServer; @@ -7,18 +7,18 @@ public class LocalSyncServerFactory { private readonly object Lock = new(); - public void CreateLocalSyncServer(AbsPipeLine pipeLine, string name,AbsPipeLine absPipeLine) + public async Task CreateLocalSyncServer( + AbsPipeLine pipeLine, + string name, + AbsPipeLine absPipeLine + ) { - var server = new LocalSyncServer( - pipeLine, - this, - name, - absPipeLine - ); + var server = new LocalSyncServer(pipeLine, this, name, absPipeLine); lock (Lock) { Servers.Add(server); } + await server.Connect(); } private readonly List Servers = []; diff --git a/Server/RemoteServer/Controllers/RemoteServerController.cs b/Server/RemoteServer/Controllers/RemoteServerController.cs index 880df31..c6f2b65 100644 --- a/Server/RemoteServer/Controllers/RemoteServerController.cs +++ b/Server/RemoteServer/Controllers/RemoteServerController.cs @@ -23,7 +23,7 @@ public class SyncFilesController(RemoteSyncServerFactory factory, SqliteDbContex { var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); var pipeLine = new WebSocPipeLine(webSocket, true); - Factory.CreateRemoteSyncServer(pipeLine, Name); + await Factory.CreateRemoteSyncServer(pipeLine, Name); } else { diff --git a/Server/RemoteServer/Program.cs b/Server/RemoteServer/Program.cs index e5cfcd6..50f5ce1 100644 --- a/Server/RemoteServer/Program.cs +++ b/Server/RemoteServer/Program.cs @@ -38,6 +38,6 @@ if (app.Environment.IsDevelopment()) } app.UseWebSockets(); app.Urls.Clear(); -app.Urls.Add("http://0.0.0.0:6818"); +app.Urls.Add("http://0.0.0.0:6819"); app.MapControllers(); app.Run(); diff --git a/Server/RemoteServer/RemoteSyncServer.cs b/Server/RemoteServer/RemoteSyncServer.cs index 925f737..76b7a40 100644 --- a/Server/RemoteServer/RemoteSyncServer.cs +++ b/Server/RemoteServer/RemoteSyncServer.cs @@ -61,24 +61,24 @@ public class RemoteSyncServer Name = name; Pwd = pwd; StateHelper = new ConnectAuthorityHelper(this); + } - Task.Run(async () => + public async Task Connect() + { + try { - try - { - var rs = Pipe.Work( - (byte[] b) => - { - return StateHelper.ReceiveMsg(b); - } - ); - await foreach (var r in rs) { } - } - catch (Exception e) - { - Close(e.Message); - } - }); + var rs = Pipe.Work( + (byte[] b) => + { + return StateHelper.ReceiveMsg(b); + } + ); + await foreach (var r in rs) { } + } + catch (Exception e) + { + Close(e.Message); + } } public void Close(string? CloseReason) diff --git a/Server/RemoteServer/RemoteSyncServerFactory.cs b/Server/RemoteServer/RemoteSyncServerFactory.cs index d71ac54..58f0389 100644 --- a/Server/RemoteServer/RemoteSyncServerFactory.cs +++ b/Server/RemoteServer/RemoteSyncServerFactory.cs @@ -10,7 +10,7 @@ public class RemoteSyncServerFactory public static List> NamePwd = []; #pragma warning restore CA2211 // Non-constant fields should not be visible - public void CreateRemoteSyncServer(AbsPipeLine pipeLine, string Name) + public async Task CreateRemoteSyncServer(AbsPipeLine pipeLine, string Name) { var pwd = NamePwd.Where(x => x.Item1 == Name).FirstOrDefault() @@ -20,6 +20,7 @@ public class RemoteSyncServerFactory { Servers.Add(server); } + await server.Connect(); } private readonly List Servers = []; diff --git a/Server/ServerTest/PipeTest.cs b/Server/ServerTest/PipeTest.cs index 2769e1b..9da6127 100644 --- a/Server/ServerTest/PipeTest.cs +++ b/Server/ServerTest/PipeTest.cs @@ -52,9 +52,17 @@ public class PipeTest RemoteSyncServer.TempRootFile = "D:/FileSyncTest/dtemp"; RemoteSyncServerFactory.NamePwd = [new Tuple("Test", "t123")]; var lf = new LocalSyncServerFactory(); - lf.CreateLocalSyncServer(p2, "Test", p3); + var task1 = Task.Run(() => + { + lf.CreateLocalSyncServer(p2, "Test", p3).RunSynchronously(); + }); + var rf = new RemoteSyncServerFactory(); - rf.CreateRemoteSyncServer(p4, "Test"); + + var task2 = Task.Run(async () => + { + await rf.CreateRemoteSyncServer(p4, "Test"); + }); TestPipe.syncServerFactory = rf; var starter = new SyncMsg { diff --git a/Tool/webtool/src/App.vue b/Tool/webtool/src/App.vue index b7d20fc..8d724ff 100644 --- a/Tool/webtool/src/App.vue +++ b/Tool/webtool/src/App.vue @@ -3,6 +3,7 @@ import MonacoEditor from 'monaco-editor-vue3'; import HistoryBtn from "./HistoryBtn.vue" import { ref, onMounted, computed } from 'vue'; import stringifyObject from 'stringify-object'; +import ConnectPipe from './connect.js' const cacheConfig = ref({}) const options = ref({ @@ -13,7 +14,7 @@ const options = ref({ const code = ref(` config = { Name: "Test", - RemoteUrl: "D:/FileSyncTest/dtemp", + RemoteUrl: "127.0.0.1:6819", RemotePwd: "t123", IsDeployDb: false, IsDeployProject: false, @@ -59,6 +60,9 @@ function submit() { } cacheConfig.value[config.Name] = config updateStorage() + var p = new ConnectPipe() + p.OpenPipe(config,()=>{}) + } catch (e) { window.alert(e) @@ -76,9 +80,6 @@ const history = computed(() => { return Object.keys(cacheConfig.value) }) -function publishCB(MsgIt) { - -} function onDel(name) { delete cacheConfig.value[name] updateStorage() @@ -86,6 +87,11 @@ function onDel(name) { function updateStorage() { localStorage.setItem('config', JSON.stringify(cacheConfig.value)) } + + +function publishCB(MsgIt) { + +} onMounted(() => { var cacheConfigStr = localStorage.getItem('config') if (cacheConfigStr) { diff --git a/Tool/webtool/src/connect.js b/Tool/webtool/src/connect.js index 2de7c96..31af00a 100644 --- a/Tool/webtool/src/connect.js +++ b/Tool/webtool/src/connect.js @@ -5,22 +5,25 @@ class ConnectPipe { //Id,Msgtype,callback // this.#websocket = new WebSocket(`ws://${window.location.host}`) } - #OpenPipe(config, MsgCb) { + OpenPipe(config, MsgCb) { this.config = config; - var webSocUrl = `ws://${window.location.host}:${window.location.port}/websoc?Name=${config.Name}` + // var webSocUrl = `ws://${window.location.host}:${window.location.port}/websoc?Name=${config.Name}` + 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)); }; this.#websocket.onmessage = (event) => { - - + console.log(event.data) }; - this.#websocket.onclose = (event) => {}; + this.#websocket.onclose = (event) => { + console.warn(event.reason) + }; this.#websocket.onerror = (e) => { + console.error(e) if (this.#websocket.readyState) { //bla bla } @@ -28,6 +31,5 @@ class ConnectPipe { } } -let cPipe = new ConnectPipe(); -export default cPipe; +export default ConnectPipe;