SOMS/TcpForwarder/MainWindow.xaml.cs
2025-03-10 18:15:27 +08:00

132 lines
3.8 KiB
C#

// MainWindow.xaml.cs 主要新增功能部分
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Windows.Threading;
using System.Windows;
using StackExchange.Redis;
public partial class MainWindow : Window
{
// 新增成员变量
private TcpListener _server;
private ConcurrentDictionary<string, TcpClient> _connectedClients = new();
private ConnectionMultiplexer _redisConnection;
// TCP 服务端启动
private async void BtnStartServer_Click(object sender, RoutedEventArgs e)
{
try
{
_server = new TcpListener(IPAddress.Any, int.Parse(txtServerPort.Text));
_server.Start();
_ = StartAcceptClientsAsync();
AppendServerLog($"服务端已启动,监听端口:{txtServerPort.Text}");
}
catch (Exception ex)
{
LogError("启动服务失败", ex);
}
}
private async Task StartAcceptClientsAsync()
{
while (_server != null)
{
var client = await _server.AcceptTcpClientAsync();
var clientId = Guid.NewGuid().ToString();
_connectedClients.TryAdd(clientId, client);
UpdateClientList();
_ = HandleClientAsync(clientId, client);
}
}
private async Task HandleClientAsync(string clientId, TcpClient client)
{
using var stream = client.GetStream();
var buffer = new byte[4096];
try
{
while (client.Connected)
{
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
AppendServerLog($"收到来自 {clientId} 的消息: {message}");
// 转发到ISMS服务端
if (_client.Connected)
{
await ForwardToIsmsAsync(message);
}
// 如果是报警消息则推送到Redis
if (IsAlertMessage(message))
{
PushToRedis(message);
}
}
}
finally
{
_connectedClients.TryRemove(clientId, out _);
UpdateClientList();
}
}
// Redis 推送
private void PushToRedis(string message)
{
if (_redisConnection?.IsConnected != true) return;
var db = _redisConnection.GetDatabase();
db.Publish("alerts", message);
AppendServerLog($"已推送报警到Redis: {message}");
}
// 测试Redis连接
//private async void TestRedisConnection_Click(object sender, RoutedEventArgs e)
//{
// var config = new ConfigurationOptions
// {
// EndPoints = { $"{txtRedisHost.Text}:{txtRedisPort.Text}" },
// Password = txtRedisAuth.Text
// };
// try
// {
// _redisConnection = await ConnectionMultiplexer.ConnectAsync(config);
// AppendServerLog("Redis连接成功");
// }
// catch (Exception ex)
// {
// LogError("Redis连接失败", ex);
// }
//}
//// 辅助方法
//private void UpdateClientList()
//{
// Dispatcher.Invoke(() =>
// {
// dgClients.ItemsSource = _connectedClients.Select(kv => new
// {
// Id = kv.Key,
// RemoteEndPoint = kv.Value.Client.RemoteEndPoint.ToString()
// }).ToList();
// });
//}
//private void AppendServerLog(string message)
//{
// Dispatcher.Invoke(() =>
// {
// txtServerLog.AppendText($"[{DateTime.Now:T}] {message}\n");
// txtServerLog.ScrollToEnd();
// });
//}
}