wenxiangchao
2026-11-02 9d1660270272180cd71147d6ddd53d1382643d2e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using TouchSocket.Core;
using TouchSocket.Sockets;
using UtilLib;
 
namespace Plugin.UICollection
{
    public enum DataType
    {
        String = 0,
        HEX = 1
    }
 
    public enum SupportEncode
    {
        GBK = 0,
        ASCII = 1,
        UTF8 = 2
    }
 
    public class EndMarkSource
    {
        public string Name { get; set; }
        public int Type { get; set; }
    }
 
    public class ByteStringConverter : IValueConverter
    {
        private TcpDebugger control { get; set; }
 
        public ByteStringConverter(TcpDebugger control)
        {
            this.control = control;
        }
 
        public static string GroupByTwo(string str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
 
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < str.Length; i += 2)
            {
                if (i > 0)
                    result.Append(' ');
 
                int length = Math.Min(2, str.Length - i);
                result.Append(str.Substring(i, length));
            }
            return result.ToString();
        }
 
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DataType sendType = control.SendDataType;
            if (sendType != DataType.HEX)
            {
                return value;
            }
            var str = value.ToString();
            return GroupByTwo(str);
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DataType sendType = control.SendDataType;
            if (sendType != DataType.HEX)
            {
                return value;
            }
            return value.ToString().Replace(" ", "");
        }
    }
 
    /// <summary>
    /// TcpDebugger.xaml 的交互逻辑
    /// </summary>
    [ObservableObject]
    public partial class TcpDebugger : UserControl
    {
 
        [ObservableProperty]
        private string ip = "127.0.0.1";
 
        [ObservableProperty]
        private int port;
 
        [ObservableProperty]
        private int clientPort;
 
        [ObservableProperty]
        private DataType receiveDataType = DataType.String;
 
        [ObservableProperty]
        private DataType sendDataType = DataType.String;
 
        [ObservableProperty]
        private bool isConnected = false;
 
        [ObservableProperty]
        private string sendText;
 
        [ObservableProperty]
        private SupportEncode receiveEncode;
 
        [ObservableProperty]
        private SupportEncode sendEncode;
 
        [ObservableProperty]
        private ObservableCollection<EndMarkSource> endMarkSource = new ObservableCollection<EndMarkSource> {
            new EndMarkSource{ Name="无",Type=-1},
            new EndMarkSource{ Name="\\r",Type=0},
            new EndMarkSource{ Name="\\r\\n",Type=1},
            new EndMarkSource{ Name="自定义",Type=2},
        };
 
        [ObservableProperty]
        private int endMark;
 
        [ObservableProperty]
        private string customEndMark;
 
        private ByteStringConverter bsConverter;
 
 
        private TcpClient client;
 
        public TcpDebugger()
        {
            DataContext = this;
            InitializeComponent();
            sendEncodeInput.ItemsSource = Enum.GetValues(typeof(SupportEncode)).Cast<SupportEncode>();
            receiveEncodeInput.ItemsSource = Enum.GetValues(typeof(SupportEncode)).Cast<SupportEncode>();
            DataObject.AddPastingHandler(sendBox, OnPasting);
            bsConverter = new ByteStringConverter(this);
            BindingOperations.SetBinding(sendBox, TextBox.TextProperty, new Binding(nameof(SendText))
            {
                Source = this,
                Mode = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Converter = bsConverter
            });
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var btn = (Button)sender;
            if (btn.Tag.ToString() == "Connect")
            {
                TryConnect();
                return;
            }
 
            if (btn.Tag.ToString() == "Send")
            {
                TrySend();
                return;
            }
 
        }
 
        private void TryConnect()
        {
            try
            {
                if (IsConnected) return;
                var config = new TouchSocketConfig().SetRemoteIPHost($"tcp://{Ip}:{Port}");
                client = new TcpClient();
                client.Received = TcpReceived;
                client.Connected = (sender, e) =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        Add("连接", "连接成功", Brushes.Green);
                        IsConnected = true;
                    });
                    return EasyTask.CompletedTask;
                };
                client.Closed = (sender, e) =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        Add("连接", "连接断开", Brushes.Red);
                        IsConnected = false;
                    });
                    return EasyTask.CompletedTask;
                };
                client.SetupAsync(config);
                client.ConnectAsync();
            }
            catch (Exception ex)
            {
                IsConnected = false;
                // throw ex;
            }
        }
 
        private Task TcpReceived(object sender, ReceivedDataEventArgs e)
        {
            try
            {
                var datas = e.Memory.Span.ToArray();
                string msg = null;
                if (ReceiveDataType == DataType.HEX)
                {
                    msg = HexUtil.ByteArrayToHex(datas);
                }
                else
                {
                    if (ReceiveEncode == SupportEncode.GBK)
                    {
                        msg = Encoding.Default.GetString(datas);
                    }
                    else if (ReceiveEncode == SupportEncode.ASCII)
                    {
                        msg = Encoding.ASCII.GetString(datas);
                    }
                    else
                    {
 
                        msg = Encoding.UTF8.GetString(datas);
                    }
                }
                Add("接收", msg, Brushes.Green);
            }
            catch (Exception ex)
            {
                //log.Error($"TcpReceived Error.", ex);
            }
            return EasyTask.CompletedTask;
        }
 
        private byte[] GetBytes(out string msg)
        {
            msg = null;
            if (string.IsNullOrEmpty(SendText))
            {
                return null;
            }
            if (SendDataType == DataType.String)
            {
                msg = SendText + GetEndMark();
                if (SendEncode == SupportEncode.GBK)
                {
                    return Encoding.Default.GetBytes(msg);
                }
                if (SendEncode == SupportEncode.ASCII)
                {
                    return Encoding.ASCII.GetBytes(msg);
                }
                if (SendEncode == SupportEncode.UTF8)
                {
                    return Encoding.UTF8.GetBytes(msg);
                }
                return null;
            }
            msg = SendText;
            if (msg.Length % 2 != 0)
            {
                msg = msg.Insert(msg.Length - 1, "0");
            }
            msg = ByteStringConverter.GroupByTwo(msg);
            return HexUtil.HexToByteArray(msg);
        }
 
        private string GetEndMark()
        {
            if (EndMark == -1)
            {
                return string.Empty;
            }
            if (EndMark == 0)
            {
                return "\r";
            }
            if (EndMark == 1)
            {
                return "\r\n";
            }
            if (EndMark == 2)
            {
                return CustomEndMark;
            }
            return string.Empty;
        }
 
        public void TrySend()
        {
            if (!IsConnected)
            {
                MessageBox.Show("请先连接", "提示");
                return;
            }
            var datas = GetBytes(out string msg);
            if (datas != null)
            {
                client.SendAsync(datas).Wait();
                Add("发送", msg, Brushes.Blue);
                // SendText = string.Empty;
            }
        }
 
        public void Add(string type, string text, Brush color)
        {
            Dispatcher.BeginInvoke(() =>
            {
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                Run run = new Run();
                run.Text = $"{time} {type}\r\n";
                run.Foreground = Brushes.Gray;
 
                Paragraph paragraph = new Paragraph(run)
                {
                    LineHeight = 1
                };
 
                run = new Run();
                run.Text = $"{text}\r\n";
                run.Foreground = color;
                paragraph.Inlines.Add(run);
                //也可以插入到最后面
                console.Document.Blocks.InsertAfter(console.Document.Blocks.LastBlock, paragraph);
 
                //插入到最前面
                //rtxtLog.Document.Blocks.Add(paragraph);
 
                // 滚动至最后行
                //rtxtLog.ScrollToEnd();
                //Console.ScrollToHome();
                console.ScrollToEnd();
                // 删除
                //if (Console.Document.Blocks.Count > 10000)
                //{
                //    for (int i = 1000; i < Console.Document.Blocks.Count; i++)
                //    {
                //        _ = Console.Document.Blocks.Remove(Console.Document.Blocks.FirstBlock);
                //    }
                //}
 
            }, System.Windows.Threading.DispatcherPriority.Normal);
        }
 
        private static readonly Regex HexRegex = new Regex("^[0-9A-Fa-f]+$");
 
        private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (SendDataType != DataType.HEX)
            {
                return;
            }
            var tb = (TextBox)sender;
            string segment = e.Text;
 
            if (!HexRegex.IsMatch(segment))
            {
                tb.Text = tb.Text.Replace(segment, "");
                tb.CaretIndex = tb.Text.Length;
                e.Handled = true;
                return;
            }
            // tb.Text = tb.Text.ToUpper();
 
            base.OnPreviewTextInput(e);
        }
 
        private void OnPasting(object sender, DataObjectPastingEventArgs e)
        {
            if (SendDataType != DataType.HEX)
            {
                return;
            }
 
            if (e.DataObject.GetDataPresent(typeof(string)))
            {
                string text = (string)e.DataObject.GetData(typeof(string));
                text = text.Replace(" ", "");
                if (!HexRegex.IsMatch(text))
                {
                    e.CancelCommand();
                }
            }
        }
    }
}