using JsonRpcLite.Network; using JsonRpcLite.Rpc; using JsonRpcLite.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WingInterfaceLibrary.Interface; using Path = System.IO.Path; namespace vStationManagementTool { public class RootObject { public Common common { get; set; } public Server server { get; set; } public List flyinsonoServers { get; set; } } public class Common { public string dateTimeFormat { get; set; } } public class Server { public string current { get; set; } public List optionSource { get; set; } } /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { private string _validationError; private string _configurePath = Path.Combine("..//", "URMWorkStation", "AppStorage", "config.conf"); private string _serverStartPath = Path.Combine("..//", "FlyinsonoLabServer", "start - 1.bat"); private string _serverClosePath = Path.Combine("..//", "FlyinsonoLabServer", "close - 1.bat"); private string _pathApp = Path.Combine("..//", "URMWorkStation"); private string _appStorage = Path.Combine("..//", "URMWorkStation", "AppStorage"); private string _pathServer = Path.Combine("..//", "FlyinsonoLabServer"); private string _versionPath= Path.Combine("..//", "StationVersion.txt"); private RootObject _root; private bool _connectStatus; private bool _isTestingServer; private bool _hasServer; public MainWindow() { InitializeComponent(); Init(); } private void Init() { var hasServer = Directory.Exists(_pathServer); _hasServer = hasServer; var isSingle = false; try { var version=File.ReadAllText(_versionPath); isSingle = version.Trim().ToLower()=="single"; } catch (Exception ex) { isSingle = _hasServer; } if (isSingle) { ServerArea.Visibility = Visibility.Visible; ClientArea.Visibility = Visibility.Collapsed; } else { ClientArea.Visibility = Visibility.Visible; ServerArea.Visibility = Visibility.Collapsed; } if (isSingle) { GetLocalIPAddress(); GetServerState(); } else { try { if (File.Exists(_configurePath)) { var data = File.ReadAllText(_configurePath); _root = JsonConvert.DeserializeObject(data); ipAddress.Text = _root.server.current.Split(':')[1].Substring(2); portNum.Text = _root.server.current.Split(':')[2]; } else { ipAddress.Text = "127.0.0.1"; portNum.Text = "8303"; if (_root == null) { _root = new RootObject(); _root.flyinsonoServers = new List(); _root.flyinsonoServers.Add("https://bj.flyinsono.com"); _root.common = new Common(); _root.server = new Server(); _root.common.dateTimeFormat = "yyyy-MM-dd HH:mm"; _root.server.current = "http://127.0.0.1:8303"; _root.server.optionSource = new List(); _root.server.optionSource.Add("http://127.0.0.1:8303"); } } } catch (Exception ex) { } } } private void GetServerState() { Task.Run(async () => { var address = ""; Dispatcher.Invoke(() => { address = "http://" + ServerIPAddress.Text + ":" + "8303"; }); var isConnected= await ValidateServerAddress(address); if (isConnected) { _connectStatus = isConnected; Dispatcher.Invoke(() => { ServerStatus.Text = "已开启"; ServerControl.Content = "关闭"; ServerIPAddress.Foreground = Brushes.Green; ServerStatus.Foreground = Brushes.Green; }); CancelBusy(); } else { _connectStatus = false; Dispatcher.Invoke(() => { if (_isTestingServer) { ServerStatus.Text = "--"; return; } else { ServerStatus.Text = "已关闭"; ServerIPAddress.Foreground = Brushes.Red; ServerControl.Content = "开启"; ServerStatus.Foreground = Brushes.Red; } }); } }); } private void portNum_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !char.IsDigit(e.Text, e.Text.Length - 1); } private void ipAddress_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !IsValidIpChar(e.Text); } private bool IsValidIpChar(string text) { // 检查是否是数字或. return char.IsDigit(text, 0) || text == "."; } public string GetLocalIPAddress() { string localIP = ""; IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } ServerIPAddress.Text= localIP; return localIP; } private async void SaveAddress_Click(object sender, RoutedEventArgs e) { var ip = ipAddress.Text; var port= portNum.Text; ValidatePort(port); if (!string.IsNullOrEmpty(_validationError)) { MessageBox.Show(owner: this, _validationError, "提示"); return; } ValidateIpAddress(ip); if (!string.IsNullOrEmpty(_validationError)) { MessageBox.Show(owner: this, _validationError, "提示"); return; } var address="http://"+ ip + ":"+port; InvokeBusy("保存中..."); var data=await ValidateServerAddress(address); CancelBusy(); if (!string.IsNullOrEmpty(_validationError)) { MessageBox.Show(owner: this, _validationError,"提示"); return; } else { _root.server.current = address; var rootText=JsonConvert.SerializeObject(_root); if (!Directory.Exists(_pathApp)) { Directory.CreateDirectory(_pathApp); } if (!Directory.Exists(_appStorage)) { Directory.CreateDirectory(_appStorage); } File.WriteAllText(_configurePath, rootText); MessageBox.Show(owner: this, "保存成功!", "提示"); } } private void ValidateIpAddress(string ipAddress) { if (!string.IsNullOrEmpty(ipAddress)) { var isIP = IPAddress.TryParse(ipAddress, out _); if (isIP) { _validationError = null; } else { _validationError = "IP 地址格式不正确!"; } } else { _validationError = null; } } private async Task ValidateServerAddress(string address) { try { InvokeBusy("检测中..."); var client = new JsonRpcClient(); var clientEngine = new JsonRpcHttpClientEngine(address); client.UseEngine(clientEngine); var loginService = client?.CreateProxy(); if (loginService != null) { _validationError = null; } else { _validationError = "服务不存在!"; } var result = await loginService.CommonLoginAsync(new WingInterfaceLibrary.Request.User.CommonLoginRequest() { }); if (result == null) { _validationError = "服务不存在!"; return false; } if (result.LoginState == WingInterfaceLibrary.Enum.LoginStateEnum.SignOrLoginFail || result.LoginState == WingInterfaceLibrary.Enum.LoginStateEnum.PasswordIncorrect ) { _validationError = null; return true; } } catch (RpcException ex) { _validationError = null; return true; } catch (Exception ex) { _validationError = "服务不存在!"; return false; } finally { if (!_isTestingServer) { CancelBusy(); } } return true; } private void ValidatePort(string port) { var success=int.TryParse(port, out int value); if (string.IsNullOrEmpty(port)||!success) { _validationError = "请输入端口号!"; } if (value <= 0 || value > 65535) { _validationError = "端口号需要在 1 到 65535!"; } else { _validationError = null; } } private void ServerControl_Click(object sender, RoutedEventArgs e) { ControlServer(ServerControl.Content == "开启"); } private void RestartServer_Click(object sender, RoutedEventArgs e) { Task.Run(() => { InvokeBusy("重启中..."); ControlServer(false,true); Thread.Sleep(3000); ControlServer(true,true); }); } private void InvokeBusy(string busyText="繁忙中...") { Dispatcher.Invoke(() => { LoaderBorder.Visibility = Visibility.Visible; IsHitTestVisible = false; ToolStatus.Text = busyText; }); } private void CancelBusy() { Dispatcher.Invoke(() => { LoaderBorder.Visibility = Visibility.Collapsed; IsHitTestVisible = true; ToolStatus.Text = "繁忙中..."; }); } private void ControlServer(bool isOpen, bool isRestart=false) { var targetPath = isOpen ? _serverStartPath : _serverClosePath; ProcessStartInfo processInfo2 = new ProcessStartInfo(targetPath) { CreateNoWindow = true, UseShellExecute=false, RedirectStandardError=true, RedirectStandardOutput=true, Verb = "runas", // 不使用操作系统外壳程序启动进程 }; Process.Start(processInfo2); Dispatcher.Invoke(() => { ServerStatus.Text = "--"; }); Task.Run (() => { if (isOpen) { int count = 0; InvokeBusy("开启中..."); _isTestingServer = true; while (_isTestingServer) { count++; Thread.Sleep(3000); InvokeBusy("开启中..."); GetServerState(); if (_connectStatus) { _isTestingServer=false; var tip = isRestart ? "服务器已重启" : "服务器已开启"; MessageBox.Show(owner: this, tip, "提示"); break; } if (count == 15) { _isTestingServer = false; CancelBusy(); Dispatcher.Invoke(() => { ServerStatus.Text = _isTestingServer ? "--" : "已关闭"; ServerIPAddress.Foreground = Brushes.Red; ServerStatus.Foreground = Brushes.Red; ServerControl.Content = "开启"; MessageBox.Show(owner: this, "服务器开启失败", "错误!"); }); break; } } CancelBusy(); } else { Task.Run(() => { InvokeBusy("关闭中..."); Thread.Sleep(3000); CancelBusy(); Dispatcher.Invoke(() => { ServerStatus.Text = "已关闭"; ServerControl.Content = "开启"; ServerIPAddress.Foreground = Brushes.Red; ServerStatus.Foreground = Brushes.Red; _connectStatus = false; if (!isRestart) { MessageBox.Show(owner: this, "服务器已关闭", "提示"); } }); }); } }); } } }