private void StartRecMsg() { try { _udpClient.BeginReceive(asyncCallback => { try { IPEndPoint iPEndPoint = null; byte[] bytes = _udpClient.EndReceive(asyncCallback, ref iPEndPoint); StartRecMsg(); HandleRecMsg?.Invoke(this, iPEndPoint, bytes); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } }
private void Start() { Task.Run(() => { while (_isRun) { try { _semaphore.WaitOne(); bool success = _taskList.TryDequeue(out Action task); if (success) { task?.Invoke(); } if (_timeSpan != TimeSpan.Zero) { Thread.Sleep(_timeSpan); } } catch (Exception ex) { HandleException?.Invoke(ex); } } }); }
/// <summary> /// 开始串口 /// </summary> public void Start() { try { if (!_sp.IsOpen) { _sp.DataReceived += new SerialDataReceivedEventHandler((a, b) => { int length = _sp.BytesToRead; byte[] buffer = new byte[length]; _sp.Read(buffer, 0, buffer.Length); HandleReceiveData?.BeginInvoke(buffer, null, null); }); _sp.Open(); HandleStarted?.Invoke(); } } catch (Exception ex) { HandleException?.Invoke(ex); } }
private void AccessException(Exception ex) { if (!(ex is ObjectDisposedException)) { HandleException?.Invoke(ex); } }
/// <summary> /// 开始Wcf服务 /// </summary> public bool StartHost() { return(Task.Factory.StartNew(() => { try { if (HandleHostOpened != null) { _serviceHost.Opened += new EventHandler(HandleHostOpened); } if (_serviceHost.State != CommunicationState.Opened) { _serviceHost.Open(); } return true; } catch (Exception ex) { HandleException?.Invoke(ex); return false; } }).Result); }
/// <summary> /// 开始服务,连接服务端 /// </summary> public void StartClient() { try { //实例化 套接字 (ip4寻址协议,流式传输,TCP协议) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建 ip对象 IPAddress address = IPAddress.Parse(_ip); //创建网络节点对象 包含 ip和port IPEndPoint endpoint = new IPEndPoint(address, _port); //将 监听套接字 绑定到 对应的IP和端口 _socket.BeginConnect(endpoint, asyncResult => { try { _socket.EndConnect(asyncResult); //开始接受服务器消息 StartRecMsg(); HandleClientStarted?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// 数据接收回调函数 /// </summary> /// <param name="ar"></param> private void ReceiveCallback(IAsyncResult ar) { UdpState udpState = ar.AsyncState as UdpState; if (ar.IsCompleted) { try { var buffer = udpState.UdpClient.EndReceive(ar, ref udpState.IpEndPoint); udpState.Buffer = buffer; HandleDataReceived?.Invoke(this, udpState); } catch (Exception ex) { HandleException?.Invoke(ex); } finally { _serverDone.Set(); if (IsRunning && _udpServer != null) { Receive(); } } } }
private void InitServer() { _tcpSocketServer.HandleServerStarted = theServer => { HandleServerStarted?.Invoke(this); }; _tcpSocketServer.HandleException = ex => { HandleException?.Invoke(ex); }; _tcpSocketServer.HandleClientClose = (theServer, theCon) => { var webCon = GetConnection(theCon.ConnectionId); CloseConnection(webCon); HandleClientClose?.Invoke(this, webCon); }; _tcpSocketServer.HandleNewClientConnected = (theServer, theCon) => { WebSocketConnection newCon = new WebSocketConnection(this, theCon) { HandleClientClose = HandleClientClose == null ? null : new Action <WebSocketServer, WebSocketConnection>(HandleClientClose), HandleSendMsg = HandleSendMsg == null ? null : new Action <WebSocketServer, WebSocketConnection, string>(HandleSendMsg) }; AddConnection(newCon); HandleNewClientConnected?.Invoke(this, newCon); }; _tcpSocketServer.HandleRecMsg = (thServer, theCon, bytes) => { string recStr = bytes.ToString(Encoding.UTF8); if (IsHandshake(recStr)) { string res = GetWebSocketResponse(recStr); theCon.Send(res); } else { int opcode = new string(bytes[0].ToBinString().Copy(4, 4).ToArray()).ToInt_FromBinString(); //为关闭连接 if (opcode == 8) { GetConnection(theCon.ConnectionId).Close(); } else { string recData = AnalyticData(bytes); HandleRecMsg?.Invoke(this, GetConnection(theCon.ConnectionId), recData); } } }; }
/// <summary> /// 关闭与服务器的连接 /// </summary> public void Close() { try { _isRec = false; _socket.Disconnect(false); HandleClientClose?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// Run a task to 'fire and forget', but to run a delegate on exception /// /// Because C# is a garbage language /// </summary> /// <param name="task">The Task to run</param> /// <param name="onError">Called if the task raises an exception</param> public static async void FireAndForget(this Task task, HandleException onException) { try { await task; } catch (Exception e) { onException?.Invoke(e); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="msg"></param> /// <param name="remote"></param> public void Send(byte[] datas, IPEndPoint remote) { try { _udpClient.Connect(remote); _udpClient.BeginSend(datas, datas.Length, new AsyncCallback(SendCallback), _udpClientState); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// 关闭串口 /// </summary> public void Stop() { try { _sp.Close(); HandleStopped?.Invoke(); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="bytes"></param> public void Send(byte[] bytes) { try { _sp.Write(bytes, 0, bytes.Length); HandleSendData?.Invoke(bytes); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// Handle task exceptions /// </summary> /// <param name="task"></param> private void HandleAggregateExceptions(Task task) { if (task?.Exception == null || _exceptionHandler == null) { return; } var aggException = task.Exception.Flatten(); foreach (var exception in aggException.InnerExceptions) { _exceptionHandler.Invoke(exception); } }
private void EndReceiveFrom(IAsyncResult ir) { if (IsListening) { UdpState state = ir.AsyncState as UdpState; try { if (ir.IsCompleted) { int length = state.Socket.EndReceiveFrom(ir, ref state.Remote); byte[] btReceived = new byte[length]; Buffer.BlockCopy(state.Buffer, 0, btReceived, 0, length); //查询是否UDP连接已经存在 SocketConnection connection = GetTheConnection(x => { var Id = (string)x.Tag; return(Id == state.Remote.ToString()); }); //如果不存在则新建一个UDP连接对象 if (connection == null) { connection = new SocketConnection(state.Remote as IPEndPoint, this) { HandleSendMsg = HandleSendMsg == null ? null : new Action <byte[], SocketConnection, SocketServer>(HandleSendMsg), HandleClientClose = new Action <SocketConnection, SocketServer>(HandleConnClientClose), HandleException = HandleException == null ? null : new Action <Exception>(HandleException) }; //connection.HandleClientClose += HandleClientClose == null ? null : new Action<SocketConnection, SocketServer>(HandleClientClose); connection.Tag = state.Remote.ToString(); AddConnection(connection); } connection.Reactive(); HandleRecMsg?.Invoke(btReceived, connection, this); } } catch (Exception ex) { //System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message + ex.Source); HandleException?.Invoke(ex); } finally { state.Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state); } } }
/// <summary> /// 开始接受客户端消息 /// </summary> public void StartRecMsg() { try { byte[] container = new byte[1024 * 1024 * 4]; _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult => { try { int length = _socket.EndReceive(asyncResult); //马上进行下一轮接受,增加吞吐量 if (length > 0 && _isRec && IsSocketConnected()) { StartRecMsg(); } if (length > 0) { byte[] recBytes = new byte[length]; Array.Copy(container, 0, recBytes, 0, length); try { //处理消息 HandleRecMsg?.BeginInvoke(recBytes, this, _server, null, null); } catch (Exception ex) { HandleException?.Invoke(ex); } } else { Close(); } } catch (Exception ex) { HandleException?.BeginInvoke(ex, null, null); Close(); } }, null); } catch (Exception ex) { HandleException?.BeginInvoke(ex, null, null); Close(); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="bytes">数据字节</param> public void Send(byte[] bytes) { try { _socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult => { try { int length = _socket.EndSend(asyncResult); HandleSendMsg?.Invoke(bytes, this); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } }
public void StartServer() { try { _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse(_ip); IPEndPoint endpoint = new IPEndPoint(address, _port); _socket.Bind(endpoint); _socket.Listen(int.MaxValue); StartListen(); HandleServerStarted?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } }
public void Close() { try { _isRec = false; _socket.Disconnect(false); _server.ClientList.Remove(this); HandleClientClose?.Invoke(this, _server); _socket.Close(); _socket.Dispose(); GC.Collect(); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// 读取消息内容 /// </summary> /// <param name="ar"></param> public void ReadBodyCallback(IAsyncResult ar) { try { String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. var bytes = new byte[bytesRead]; Array.Copy(state.buffer, 0, state.data, state.dataRecviedLen, bytesRead); state.dataRecviedLen += bytesRead; if (state.dataRecviedLen < state.dataLen) { _socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReadBodyCallback), state); } else { try { HandleRecMsg?.BeginInvoke(state.data, this, _server, null, null); } catch (Exception ex) { HandleException?.Invoke(ex); } if (_isRec && IsSocketConnected()) { StartRecMsg(); } } } } catch (Exception ex) { HandleException?.BeginInvoke(ex, null, null); Close(); } }
/// <summary> /// 关闭当前连接 /// </summary> public void Close() { if (_isClosed) { return; } try { _isClosed = true; _server.RemoveConnection(this); _isRec = false; _socket.BeginDisconnect(false, (asyncCallback) => { try { _socket.EndDisconnect(asyncCallback); } catch (Exception ex) { HandleException?.Invoke(ex); } finally { _socket.Dispose(); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } finally { try { HandleClientClose?.Invoke(_server, this); } catch (Exception ex) { HandleException?.Invoke(ex); } } }
private void SendCallback(IAsyncResult ar) { UdpState udpState = ar.AsyncState as UdpState; if (ar.IsCompleted) { try { udpState.UdpClient.EndSend(ar); } catch (Exception ex) { HandleException?.Invoke(ex); } finally { } } }
private void StartListen() { try { _socket.BeginAccept(asyncResult => { try { Socket newSocket = _socket.EndAccept(asyncResult); //马上进行下一轮监听,增加吞吐量 if (_isListen) { StartListen(); } TcpSocketConnection newConnection = new TcpSocketConnection(newSocket, this, RecLength) { HandleRecMsg = HandleRecMsg == null ? null : new Action <TcpSocketServer, TcpSocketConnection, byte[]>(HandleRecMsg), HandleClientClose = HandleClientClose == null ? null : new Action <TcpSocketServer, TcpSocketConnection>(HandleClientClose), HandleSendMsg = HandleSendMsg == null ? null : new Action <TcpSocketServer, TcpSocketConnection, byte[]>(HandleSendMsg), HandleException = HandleException == null ? null : new Action <Exception>(HandleException) }; newConnection.HandleRecMsg += new Action <TcpSocketServer, TcpSocketConnection, byte[]>((a, b, c) => { _sendCheckMsg.RecMsg(b.ConnectionId, c); }); AddConnection(newConnection); newConnection.StartRecMsg(); HandleNewClientConnected?.Invoke(this, newConnection); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } }
private RESPONSE PostObject <REQUEST, RESPONSE>(string url, REQUEST req, HandleException handleException, HandleErrorMessage handleErrorMessage, bool isDoradoMsg = true) { string jsonData = JsonConvert.SerializeObject(req); RestResponse response = null; try { response = restClient.PostObject(url, jsonData); if (response.StatusCode >= HttpStatusCode.BadRequest) { log.InfoFormat("Failed to post, status code: {0}, url: {1}", response.StatusCode, url); if (handleErrorMessage == null) { HandleErrorMessageDefault(response, false, isDoradoMsg); } else { handleErrorMessage(response); } return(default(RESPONSE)); } return(JsonConvert.DeserializeObject <RESPONSE>(response.Content)); } catch (Exception ex) { log.ErrorFormat("Failed to post object, exception:{0}", ex); log.InfoFormat("Failed to post, url:{0}", url); if (null == response) { log.Info("The response is null for post object"); } else { log.InfoFormat("Failed to post object, the response is {0}", response.Content); } handleException?.Invoke(ex); } return(default(RESPONSE)); }
private bool DeleteObject(string url, HandleException handleException, HandleErrorMessage handleErrorMessage, bool isDoradoMsg = true) { bool result = true; RestResponse response = null; try { response = restClient.DeleteObject(url); if (response.StatusCode >= HttpStatusCode.BadRequest) { log.InfoFormat("Failed to delete, status code: {0}, url: {1}", response.StatusCode, url); if (handleErrorMessage == null) { HandleErrorMessageDefault(response, false, isDoradoMsg); } else { handleErrorMessage(response); } result = false; } } catch (Exception ex) { log.ErrorFormat("Failed to delete object, exception:{0}", ex); log.InfoFormat("Failed to delete, url:{0}", url); if (null == response) { log.Info("The response is null for delete object"); } else { log.InfoFormat("Failed to delete object, the response is {0}", response.Content); } handleException?.Invoke(ex); result = false; } return(result); }
private void StartListen() { try { _socket.BeginAccept(asyncResult => { try { Socket newSocket = _socket.EndAccept(asyncResult); if (_isListen) { StartListen(); } SocketConnection newClient = new SocketConnection(newSocket, this) { HandleRecMsg = HandleRecMsg == null ? null : new Action <byte[], SocketConnection, SocketServer>(HandleRecMsg), HandleClientClose = HandleClientClose == null ? null : new Action <SocketConnection, SocketServer>(HandleClientClose), HandleSendMsg = HandleSendMsg == null ? null : new Action <byte[], SocketConnection, SocketServer>(HandleSendMsg), HandleException = HandleException == null ? null : new Action <Exception>(HandleException) }; newClient.StartRecMsg(); ClientList.AddLast(newClient); HandleNewClientConnected?.Invoke(this, newClient); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// 发送数据 /// </summary> /// <param name="bytes">数据</param> /// <param name="iPEndPoint">目标地址</param> public void Send(byte[] bytes, IPEndPoint iPEndPoint) { try { _udpClient.BeginSend(bytes, bytes.Length, iPEndPoint, asyncCallback => { try { int length = _udpClient.EndSend(asyncCallback); HandleSendMsg?.Invoke(this, iPEndPoint, bytes); } catch (Exception ex) { HandleException?.Invoke(ex); } }, null); } catch (Exception ex) { HandleException?.Invoke(ex); } }
/// <summary> /// 开始服务,监听客户端 /// </summary> public void StartServer() { try { //实例化套接字(ip4寻址协议,流式传输,TCP协议) _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建ip对象 IPAddress address = IPAddress.Parse(_ip); //创建网络节点对象包含ip和port IPEndPoint endpoint = new IPEndPoint(address, _port); //将 监听套接字绑定到 对应的IP和端口 _socket.Bind(endpoint); //设置监听队列长度为Int32最大值(同时能够处理连接请求数量) _socket.Listen(int.MaxValue); //开始监听客户端 StartListen(); HandleServerStarted?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } }
protected virtual void OnDrawRaffleVictor(PaymentClass paymentClass) { try { CanExecuteRaffle = false; WinningTicket = null; CancellationTokenSource cts = new CancellationTokenSource(); //todo: find a better way to handle this asynchronously Task.Run(() => { BeginUIWait(paymentClass, cts.Token); }); Task.Run(async() => { var ticket = RaffleService.GetRandomTicket(paymentClass); await Task.Delay(TimeSpan.FromSeconds(3)); return(ticket); }) .ContinueWith((t) => { cts.Cancel(); WinningTicket = t.Result; CanExecuteRaffle = true; }); } catch (Exception ex) { HandleException?.Invoke(this, ex); } }
/// <summary> /// 关闭与服务器的连接 /// </summary> public void Close() { try { _isRec = false; _socket.BeginDisconnect(false, asyncCallback => { try { _socket.EndDisconnect(asyncCallback); } catch (Exception ex) { HandleException?.BeginInvoke(ex, null, null); } finally { _socket.Dispose(); } }, null); } catch (Exception ex) { HandleException?.BeginInvoke(ex, null, null); } finally { try { HandleClientClose?.Invoke(this); } catch (Exception ex) { HandleException?.Invoke(ex); } } }