public void Stop() { Log4.Debug("Serial Server Stop"); Dispose(true); SetStatus(ServiceStatus.Stopped); }
static void Main() { log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(("log4net.config"))); Log4.Debug("startup"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmMain()); }
private static void LogDebug(string log) { Log4.Debug(log); AppReportManager.Instance.Send(new LogEntity() { Log = log }); }
public void Stop() { Log4.Debug("Serial Server Stop"); TelemetryService.Instance.TrackEvent("SerialServer Stop"); Dispose(true); SetStatus(ServiceStatus.Stopped); }
//----------------------------------------------------------- // Async handlers //----------------------------------------------------------- private void OnClientConnect(IAsyncResult async) { Log4.Debug("SocketServer OnClientConnect"); if (_mainSocket == null) { return; } ServerReplyContext serverReplyContext = null; try { // Here we complete/end the BeginAccept() asynchronous call // by calling EndAccept() - which returns the reference to // a new Socket object var workerSocket = _mainSocket.EndAccept(async); // Now increment the client count for this client // in a thread safe manner Interlocked.Increment(ref _clientCount); // Add the workerSocket reference to the list _clientList.GetOrAdd(_clientCount, workerSocket); serverReplyContext = new ServerReplyContext(this, workerSocket, _clientCount); Log4.Debug("Opened Socket #" + _clientCount); SetStatus(ServiceStatus.Connected); SendNotification(ServiceNotification.ClientConnected, CurrentStatus, serverReplyContext); // Send a welcome message to client // TODO: Notify client # & IP address //string msg = "Welcome client " + _clientCount + "\n"; //SendMsgToClient(msg, m_clientCount); // Let the worker Socket do the further processing for the // just connected client BeginReceive(serverReplyContext); } catch (SocketException se) { SendNotification(ServiceNotification.Error, CurrentStatus, serverReplyContext, $"OnClientConnect: {se.Message}, {se.HResult:X} ({se.SocketErrorCode})"); // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx //if (se.SocketErrorCode == SocketError.ConnectionReset) // WSAECONNRESET (10054) { // Forcibly closed CloseSocket(serverReplyContext); } } catch (Exception e) { SendNotification(ServiceNotification.Error, CurrentStatus, serverReplyContext, $"OnClientConnect: {e.Message}"); CloseSocket(serverReplyContext); } // Since the main Socket is now free, it can go back and wait for // other clients who are attempting to connect _mainSocket?.BeginAccept(OnClientConnect, null); }
/// <summary> /// 后置拦截器 /// </summary> /// <param name="ctx"></param> /// <returns></returns> private void AfterRequest(NancyContext ctx) { string log = $"End [Method]{ctx.Request.Method},[Url]{ctx.Request.Url}"; Log4.Debug(log); AppReportManager.Instance.Send(new LogEntity() { Log = log }); }
/// <summary> /// 前置拦截器 /// </summary> /// <param name="ctx"></param> /// <returns></returns> private Response BeforeRequest(NancyContext ctx) { string path = ctx.ResolvedRoute.Description.Path; //string log = $"请求开始[Method]{ctx.Request.Method},[Path]{ctx.Request.Path},[Query]{JsonDynamicUtil.ToJson(ctx.Request.Query)},[Url]{ctx.Request.Url}"; string log = $"Start [Method]{ctx.Request.Method},[Url]{ctx.Request.Url}"; Log4.Debug(log); AppReportManager.Instance.Send(new LogEntity() { Log = log }); return(null); }
private Response Run(dynamic _) { //var name = Request.Query["Name"];//get请求获取方法 string msg = getPara("path"); System.Diagnostics.Process proc = System.Diagnostics.Process.Start(msg); Log4.Debug("成功"); AppReportManager.Instance.Send(new LogEntity() { Log = "成功" }); return(Success("成功")); }
// Start waiting for data from the client private void BeginReceive(ServerReplyContext serverReplyContext) { Log4.Debug("SocketServer BeginReceive"); try { _ = serverReplyContext.Socket.BeginReceive(serverReplyContext.DataBuffer, 0, serverReplyContext.DataBuffer.Length, SocketFlags.None, OnDataReceived, serverReplyContext); } catch (SocketException se) { SendNotification(ServiceNotification.Error, CurrentStatus, serverReplyContext, $"BeginReceive: {se.Message}, {se.HResult:X} ({se.SocketErrorCode})"); CloseSocket(serverReplyContext); } }
//----------------------------------------------------------- // Control functions (Start, Stop, etc...) //----------------------------------------------------------- public void Start(String portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake) { TelemetryService.Instance.TrackEvent("SerialServer Start", properties: new Dictionary <string, string> { { "settings", $"{GetSettingsDisplayString()}" } }); if (_serialPort != null || _readThread != null) { Stop(); } Debug.Assert(_serialPort == null); Debug.Assert(_readThread == null); _serialPort = new SerialPort { PortName = portName, BaudRate = baudRate, Parity = parity, DataBits = dataBits, StopBits = stopBits, Handshake = handshake, ReadTimeout = 500 }; try { // Set the read/write timeouts Log4.Debug("Opening serial port: " + GetSettingsDisplayString()); SetStatus(ServiceStatus.Started, GetSettingsDisplayString()); _serialPort.Open(); _readThread = new Thread(Read); _readThread.Start(); SetStatus(ServiceStatus.Waiting); } catch (IOException ioe) { Error(ioe.Message); Stop(); } catch (UnauthorizedAccessException uae) { Error($"Port in use? {uae.Message} ({GetSettingsDisplayString()})"); Stop(); } catch (Exception e) { Error(e.Message); Stop(); } }
private Response dc_SelfServiceDeviceCardEject(dynamic _) { int res = dcrf.dc_SelfServiceDeviceCardEject((IntPtr)AppCfg.Instance.Handle, Convert.ToByte(30), System.Convert.ToByte("0x00", 16)); Log4.Debug($"弹卡:{res}"); AppReportManager.Instance.Send(new LogEntity() { Log = $"弹卡:{res}" }); if (res <= 0) { return(Fail($"失败")); } else { return(Success("成功")); } }
private Response Dc_Exit(dynamic _) { int res = dcrf.dc_exit((IntPtr)AppCfg.Instance.Handle); Log4.Debug($"关闭端口:{res}"); AppReportManager.Instance.Send(new LogEntity() { Log = $"关闭端口:{res}" }); if (res <= 0) { return(Fail($"失败")); } else { return(Success("成功")); } }
private void Read() { Log4.Debug($"Serial Read thread starting: {GetSettingsDisplayString()}"); StringBuilder sb = new StringBuilder(); while (true) { try { if (_serialPort == null) { Log4.Debug("_serialPort is null in Read()"); break; } char c = (char)_serialPort.ReadChar(); if (c == '\r' || c == '\n' || c == '\0') { string cmd = sb.ToString(); sb.Length = 0; if (cmd.Length > 0) { SendNotification(ServiceNotification.ReceivedData, CurrentStatus, new SerialReplyContext(_serialPort), cmd); } } else { sb.Append(c); } } catch (TimeoutException) { Log4.Debug("SerialServer: TimeoutException"); } catch (IOException ioe) { Log4.Debug("SerialServer: IOException: " + ioe.Message); } catch (Exception e) { Log4.Debug("SerialServer: Exception: " + e.Message); } } Log4.Debug("SerialServer: Exiting Read()"); }
private void CloseSocket(ServerReplyContext serverReplyContext) { Log4.Debug("SocketServer CloseSocket"); if (serverReplyContext == null) { return; } // Remove the reference to the worker socket of the closed client // so that this object will get garbage collected _ = _clientList.TryRemove(serverReplyContext.ClientNumber, out var socket); if (socket != null) { Log4.Debug("Closing Socket #" + serverReplyContext.ClientNumber); Interlocked.Decrement(ref _clientCount); SendNotification(ServiceNotification.ClientDisconnected, CurrentStatus, serverReplyContext); socket.Close(); } }
private void Dispose(bool disposing) { Log4.Debug("SocketServer disposing..."); if (!disposing) { return; } foreach (var i in _clientList.Keys) { _clientList.TryRemove(i, out var socket); if (socket != null) { Log4.Debug("Closing Socket #" + i); socket.Close(); } } _mainSocket?.Close(); _mainSocket = null; }
private Response cardexitx(dynamic _) { try { //加锁防止并发调用 lock (obj) { //打开端口 var port = ConfigurationManager.AppSettings["Port"]; var baud = ConfigurationManager.AppSettings["Baud"]; IntPtr handle = dcrf.dc_init(Convert.ToInt32(port), Convert.ToInt32(baud)); if ((int)handle <= 0) { } else { AppCfg.Instance.Handle = (int)handle; AppCfg.Instance.Save(); } //弹卡 int res1 = dcrf.dc_SelfServiceDeviceCardEject((IntPtr)AppCfg.Instance.Handle, Convert.ToByte(30), System.Convert.ToByte("0x00", 16)); //关闭端口 var res2 = dcrf.dc_exit((IntPtr)AppCfg.Instance.Handle); Log4.Debug($"打开端口:{(int)handle},弹卡:{res1},关闭端口:{res2}"); AppReportManager.Instance.Send(new LogEntity() { Log = $"打开端口:{(int)handle},弹卡:{res1},关闭端口:{res2}" }); return(Success(new { log = $"打开端口:{(int)handle},弹卡:{res1},关闭端口:{res2}" })); } } catch (Exception e) { Log4.Error(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo) + "[程序异常]" + e.ToString()); return(Fail(e.ToString())); } }
//----------------------------------------------------------- // Control functions (Start, Stop, etc...) //----------------------------------------------------------- public void Start(int port) { try { // Create the listening socket... _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var ipLocal = new IPEndPoint(IPAddress.Any, port); // Bind to local IP Address... Log4.Debug("SocketServer - Binding to IP address: " + ipLocal.Address + ":" + ipLocal.Port); _mainSocket.Bind(ipLocal); // Start listening... Log4.Debug("_mainSocket.Listen"); _mainSocket.Listen(4); // Create the call back for any client connections... SetStatus(ServiceStatus.Started, $"{ipLocal.Address}:{port}"); SetStatus(ServiceStatus.Waiting); _mainSocket.BeginAccept(OnClientConnect, null); } catch (SocketException se) { SendNotification(ServiceNotification.Error, CurrentStatus, null, $"{se.Message}, {se.HResult:X} ({se.SocketErrorCode})"); SetStatus(ServiceStatus.Stopped); } }
public Response Dc_Init(dynamic _) { var port = ConfigurationManager.AppSettings["Port"]; var baud = ConfigurationManager.AppSettings["Baud"]; IntPtr handle = dcrf.dc_init(Convert.ToInt32(port), Convert.ToInt32(baud)); Log4.Debug($"打开端口:{(int)handle}"); AppReportManager.Instance.Send(new LogEntity() { Log = $"打开端口:{(int)handle}" }); if ((int)handle <= 0) { return(Fail("失败")); } else { AppCfg.Instance.Handle = (int)handle; AppCfg.Instance.Save(); return(Success("成功")); } }
private Response Call(dynamic _) { //var name = Request.Query["Name"];//get请求获取方法 string msg = getPara("msg"); int iErr = Jtts.jTTS_Play(msg, 0); if (Jtts.ERR_NONE != iErr) { Log4.Debug("错误号" + iErr); AppReportManager.Instance.Send(new LogEntity() { Log = "错误号" + iErr }); return(Fail("错误号" + iErr)); } Log4.Debug("成功"); AppReportManager.Instance.Send(new LogEntity() { Log = "成功" }); return(Success("成功")); }
static void Main() { try { log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(("log4net.config"))); AppCfg.FileName = Application.StartupPath + "\\config.yl"; Log4.Debug("startup"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); System.Threading.Mutex mutex = new System.Threading.Mutex(true, "c9d85cde-f58e-49fa-a99a-7b79e71a0de6", out bool ret); if (ret) { //处理未捕获的异常 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); //处理非UI线程异常 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.Run(new FrmMain()); glExitApp = true;//标志应用程序可以退出 mutex.ReleaseMutex(); } else { //MessageBox.Show(null, "有一个和本程序相同的应用程序已经在运行,请不要同时运行多个本程序。\n\n这个程序即将退出。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); // 提示信息,可以删除。 Application.Exit();//退出程序 } } catch (Exception e) { Log4.Error(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo) + "[程序崩溃]" + GetExceptionMsg(e, string.Empty)); } }
private void Connect() { IPEndPoint endPoint; try { // GetHostEntry returns a list. We need to pick the IPv4 entry. // TODO: Support ipv6 var ipv4Addresses = Array.FindAll(Dns.GetHostEntry(_host).AddressList, a => a.AddressFamily == AddressFamily.InterNetwork); if (ipv4Addresses.Length == 0) { throw new IOException($"{_host}:{_port} didn't resolve to a valid address"); } endPoint = new IPEndPoint(ipv4Addresses[0], _port); // TELEMETRY: Do not pass _host to SetStatus to avoid collecting PII SetStatus(ServiceStatus.Started, $"{ipv4Addresses[0]}:{_port}"); _ = _tcpClient.BeginConnect(endPoint.Address, _port, ar => { if (_tcpClient == null) { return; } try { Log4.Debug($"Client BeginConnect: { _host}:{ _port}"); _tcpClient.EndConnect(ar); Log4.Debug($"Client Back from EndConnect: { _host}:{ _port}"); SetStatus(ServiceStatus.Connected, $"{_host}:{_port}"); StringBuilder sb = new StringBuilder(); while (_bw != null && !_bw.CancellationPending && CurrentStatus == ServiceStatus.Connected && _tcpClient != null && _tcpClient.Connected) { // TODO: Move exception handling around this int input = _tcpClient.GetStream().ReadByte(); switch (input) { case (byte)'\r': case (byte)'\n': case (byte)'\0': if (sb.Length > 0) { SendNotification(ServiceNotification.ReceivedData, ServiceStatus.Connected, new ClientReplyContext(_tcpClient), sb.ToString()); sb.Clear(); System.Threading.Thread.Sleep(100); } break; case -1: Error("No more data."); return; default: sb.Append((char)input); break; } } } catch (SocketException e) { Log4.Debug($"SocketClient: {e.GetType().Name}: {e.Message}"); CatchSocketException(e); } catch (IOException e) { if (e.InnerException is SocketException sockExcept) { CatchSocketException(sockExcept); } else { Error($"SocketClient: {e.GetType().Name}: {e.Message}"); } } catch (Exception e) { // Got this when endPoint = new IPEndPoint(Dns.GetHostEntry(_host).AddressList[0], _port) // resolved to an ipv6 address Log4.Debug($"SocketClient Generic Exception: {e.GetType().Name}: {e.Message}"); Error($"SocketClient Generic Exception: {e.GetType().Name} {e.Message}"); } finally { //log4.Debug("finally - Stopping"); //Stop(); } }, null); } catch (SocketException e) { Log4.Debug($"SocketClient: (BeginConnect) {e.GetType().Name}: {e.Message}"); CatchSocketException(e); if (_tcpClient != null) { _tcpClient.Close(); } return; } catch (Exception e) { Log4.Debug($"SocketClient: (BeginConnect){e.GetType().Name}: {e.Message}"); Error($"SocketClient: (BeginConnect) Generic Exception: {e.GetType().Name}: {e.Message}"); if (_tcpClient != null) { _tcpClient.Close(); } return; } Log4.Debug("BeginConnect returned"); }
public void SendAwakeCommand(String cmd, String host, int port) { Log4.Debug("SocketServer SendAwakeCommand"); if (String.IsNullOrEmpty(host)) { SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, "No wakeup host specified"); return; } if (port == 0) { SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, "Invalid port"); return; } try { // Try to resolve the remote host name or address var resolvedHost = Dns.GetHostEntry(host); var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { // Create the endpoint that describes the destination var destination = new IPEndPoint(resolvedHost.AddressList[0], port); SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, $"Attempting connection to: {destination}"); clientSocket.Connect(destination); } catch (SocketException err) { // Connect failed so close the socket and try the next address clientSocket.Close(); clientSocket = null; SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, "Error connecting.\r\n" + $" Error: {err.Message}"); } // Make sure we have a valid socket before trying to use it if ((clientSocket != null)) { try { _ = clientSocket.Send(Encoding.ASCII.GetBytes(cmd + "\r\n")); SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, "Sent request " + cmd + " to wakeup host."); // For TCP, shutdown sending on our side since the client won't send any more data clientSocket.Shutdown(SocketShutdown.Send); } catch (SocketException err) { SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, $"Error occured while sending or receiving data.\r\n Error: {err.Message}"); } clientSocket.Dispose(); } else { SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, "Unable to establish connection to server!"); } } catch (SocketException err) { SendNotification(ServiceNotification.Wakeup, CurrentStatus, null, $"Socket error occured: {err.Message}"); } }
// Send an error notification protected void Error(String msg) { Log4.Debug(msg); Notifications?.Invoke(ServiceNotification.Error, CurrentStatus, null, msg); }