电子药箱通讯服务端
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

MainWindow.xaml.cs 6.7KB

7 месяцев назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.Collections.ObjectModel;
  16. using System.ComponentModel;
  17. using TouchSocket.Core;
  18. using TouchSocket.Sockets;
  19. using System.Threading;
  20. using System.Configuration;
  21. namespace Tcp.Test2
  22. {
  23. /// <summary>
  24. /// Interaction logic for MainWindow.xaml
  25. /// </summary>
  26. public partial class MainWindow : Window, INotifyPropertyChanged
  27. {
  28. private ObservableCollection<MessageModel> _listMessages;
  29. private ICommand _sendCommand;
  30. private String _currentInput;
  31. private String _statusMessage;
  32. private TcpClient _tcpClient;
  33. private Encoding _encoding;
  34. private TouchSocketConfig _tcpClientConfig;
  35. private static readonly String _serverIP, _serverPort;
  36. public MainWindow()
  37. {
  38. InitializeComponent();
  39. this.DataContext = this;
  40. this.Loaded += MainWindow_Loaded;
  41. }
  42. static MainWindow()
  43. {
  44. _serverIP = ConfigurationManager.AppSettings["ServerIp"];
  45. if (String.IsNullOrWhiteSpace(_serverIP))
  46. {
  47. _serverIP = "127.0.0.1";
  48. }
  49. _serverPort = ConfigurationManager.AppSettings["ServerPort"];
  50. if (String.IsNullOrWhiteSpace(_serverPort))
  51. {
  52. _serverPort = "8308";
  53. }
  54. }
  55. public event PropertyChangedEventHandler? PropertyChanged;
  56. public ObservableCollection<MessageModel> ListMessage
  57. {
  58. get { return _listMessages; }
  59. set
  60. {
  61. _listMessages = value;
  62. OnPropertyChanged(nameof(ListMessage));
  63. }
  64. }
  65. public ICommand SendCommand
  66. {
  67. get { return _sendCommand; }
  68. set
  69. {
  70. _sendCommand = value;
  71. OnPropertyChanged(nameof(SendCommand));
  72. }
  73. }
  74. public String CurrentInput
  75. {
  76. get { return _currentInput; }
  77. set
  78. {
  79. _currentInput = value;
  80. OnPropertyChanged(nameof(CurrentInput));
  81. }
  82. }
  83. public String StatusMessage
  84. {
  85. get { return _statusMessage; }
  86. set
  87. {
  88. _statusMessage = value;
  89. OnPropertyChanged(nameof(StatusMessage));
  90. }
  91. }
  92. private void MainWindow_Loaded(object sender, RoutedEventArgs e)
  93. {
  94. this.SendCommand = new DelegateCommand(this.SendCommandHandler);
  95. this.ListMessage = new ObservableCollection<MessageModel>();
  96. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  97. _encoding = Encoding.GetEncoding("gb2312");
  98. //声明配置
  99. _tcpClientConfig = new TouchSocketConfig();
  100. _tcpClientConfig.SetRemoteIPHost(new IPHost($"{_serverIP}:{_serverPort}"))
  101. //config.SetRemoteIPHost(new IPHost("192.168.2.253:8308"))
  102. .UsePlugin()
  103. .ConfigurePlugins(a =>
  104. {
  105. a.UseReconnection(5, true, 1000);
  106. })
  107. .SetBufferLength(1024 * 10);
  108. _tcpClient = CreateClient();
  109. //载入配置
  110. Task.Run(() =>
  111. {
  112. ConnectServer();
  113. });
  114. }
  115. private void OnPropertyChanged(String propertyName)
  116. {
  117. if (PropertyChanged != null)
  118. {
  119. PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  120. }
  121. }
  122. private TouchSocket.Sockets.TcpClient CreateClient()
  123. {
  124. if (_tcpClient != null)
  125. {
  126. _tcpClient.Dispose();
  127. }
  128. _tcpClient = new TouchSocket.Sockets.TcpClient();
  129. _tcpClient.Setup(_tcpClientConfig);
  130. _tcpClient.Connected += (client, e) =>
  131. {
  132. Application.Current.Dispatcher.Invoke(() =>
  133. {
  134. this.StatusMessage = "成功连接服务器";
  135. });
  136. };//成功连接到服务器
  137. _tcpClient.Disconnected += (client, e) =>
  138. {
  139. Application.Current.Dispatcher.Invoke(() =>
  140. {
  141. this.StatusMessage = "与服务器断开连接";
  142. });
  143. _tcpClient = CreateClient();
  144. };//从服务器断开连接,当连接不成功时不会触发。
  145. _tcpClient.Received += (client, byteBlock, requestInfo) =>
  146. {
  147. //从服务器收到信息
  148. string mes = _encoding.GetString(byteBlock.Buffer, 0, byteBlock.Len);
  149. Application.Current.Dispatcher.Invoke(() =>
  150. {
  151. ListMessage.Add(new MessageModel
  152. {
  153. IsAck = true,
  154. Message = mes
  155. });
  156. });
  157. };
  158. return _tcpClient;
  159. }
  160. private void ConnectServer()
  161. {
  162. while (true)
  163. {
  164. if (_tcpClient != null)
  165. {
  166. if (!_tcpClient.Online)
  167. {
  168. Console.WriteLine("正在连接服务器...");
  169. try
  170. {
  171. _tcpClient.Connect();
  172. Console.WriteLine("连接成功");
  173. }
  174. catch (Exception ex)
  175. {
  176. Console.WriteLine("连接失败:" + ex.Message);
  177. Thread.Sleep(1000);
  178. }
  179. }
  180. }
  181. Thread.Sleep(1000);
  182. }
  183. }
  184. private void SendCommandHandler()
  185. {
  186. if (!String.IsNullOrWhiteSpace(this._currentInput))
  187. {
  188. try
  189. {
  190. _tcpClient.Send(_encoding.GetBytes(this._currentInput));
  191. this.StatusMessage = String.Empty;
  192. ListMessage.Add(new MessageModel()
  193. {
  194. Message = this._currentInput
  195. });
  196. }
  197. catch (Exception ex)
  198. {
  199. this.StatusMessage = "发送失败:" + ex.Message;
  200. }
  201. }
  202. }
  203. }
  204. }