FileSqlServerSync/Server/LocalServer/LocalSyncServer.cs
2024-10-12 22:01:48 +08:00

209 lines
5.5 KiB
C#

using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using Common;
namespace LocalServer;
public class LocalSyncServer
{
#pragma warning disable CA2211 // Non-constant fields should not be visible
public static string TempRootFile = "C:/TempPack";
#pragma warning restore CA2211 // Non-constant fields should not be visible
public StateHelpBase StateHelper;
public Config? SyncConfig;
public Config NotNullSyncConfig {get {
if (SyncConfig == null)
{
throw new ArgumentNullException("SyncConfig");
}
return SyncConfig;
}}
/// <summary>
/// 发布源连接
/// </summary>
public readonly WebSocket LocalSocket;
/// <summary>
/// 发布源-缓冲区,存储数据 最大1MB
/// </summary>
// public byte[] Buffer = new byte[1024 * 1024];
/// <summary>
/// 发布目标-连接
/// </summary>
public readonly ClientWebSocket RemoteSocket = new();
/// <summary>
/// 发布开始时间
/// </summary>
private readonly DateTime StartTime = DateTime.Now;
/// <summary>
/// 发布名称
/// </summary>
public readonly string Name;
/// <summary>
/// 父工程,用于释放资源
/// </summary>
public readonly LocalSyncServerFactory Factory;
public LocalSyncServer(WebSocket socket, string name, LocalSyncServerFactory factory)
{
LocalSocket = socket;
Name = name;
Factory = factory;
StateHelper = new ConnectAuthorityHelper(this);
}
public async Task RemoteSocketConnect()
{
if (SyncConfig != null)
{
await RemoteSocket.ConnectAsync(
new Uri(SyncConfig.RemoteUrl + "/websoc"),
CancellationToken.None
);
}
else
{
throw new ArgumentException("SyncConfig is null!");
}
}
public async Task RemoteSocketLiten()
{
string CloseMsg = "任务结束关闭";
try
{
while (RemoteSocket.State == WebSocketState.Open)
{
var buffer = new byte[1024 * 1024];
var receiveResult = await RemoteSocket.ReceiveAsync(
new ArraySegment<byte>(buffer),
CancellationToken.None
);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
Close(receiveResult.CloseStatusDescription);
}
else
{
var nbuffer = new byte[receiveResult.Count];
System.Buffer.BlockCopy(buffer, 0, nbuffer, 0, receiveResult.Count);
StateHelper.ReceiveRemoteMsg(nbuffer);
}
}
}
catch (Exception e)
{
CloseMsg = e.Message;
}
finally
{
Close(CloseMsg);
}
}
public async Task LocalSocketListen()
{
string CloseMsg = "任务结束关闭";
try
{
//最大1MB!=
var buffer = new byte[1024 * 1024];
while (LocalSocket.State == WebSocketState.Open)
{
var receiveResult = await LocalSocket.ReceiveAsync(
new ArraySegment<byte>(buffer),
CancellationToken.None
);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
Close(receiveResult.CloseStatusDescription);
}
else
{
StateHelper.ReceiveLocalMsg(
Encoding.UTF8.GetString(buffer, 0, receiveResult.Count)
);
}
}
}
catch (Exception e)
{
CloseMsg = e.Message;
}
finally
{
Close(CloseMsg);
}
}
public async Task LocalSocketSendMsg(object msgOb)
{
string msg = JsonSerializer.Serialize(msgOb);
await LocalSocket.SendAsync(
new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg)),
WebSocketMessageType.Text,
true,
CancellationToken.None
);
}
public async Task RemoteSocketSendMsg(object msgOb)
{
string msg = JsonSerializer.Serialize(msgOb);
var buffer = AESHelper.EncryptStringToBytes_Aes(msg);
await RemoteSocket.SendAsync(
buffer,
WebSocketMessageType.Text,
true,
CancellationToken.None
);
}
public void Close(string? CloseReason)
{
try
{
if (LocalSocket.State == WebSocketState.Open)
{
LocalSocket
.CloseAsync(
WebSocketCloseStatus.NormalClosure,
CloseReason,
CancellationToken.None
)
.Wait(60 * 1000);
}
if (RemoteSocket.State == WebSocketState.Open)
{
RemoteSocket
.CloseAsync(
WebSocketCloseStatus.NormalClosure,
CloseReason,
CancellationToken.None
)
.Wait(60 * 1000);
}
}
catch (Exception e)
{
//TODO 日志
Console.WriteLine(e.Message);
}
finally
{
Factory.RemoveLocalSyncServer(this);
}
}
}