static Packet() { Fragment = Platform.CoreFragment?.GetPacketFragment() ?? throw Platform.FragmentException(); Fragment.Process = args => OnProcess.SafeInvoke(args); Fragment.Send = args => OnSend.SafeInvoke(args); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (this._apiKey != null) { request.Headers.Add("X-Api-Key", this._apiKey); } IEndpoint endpoint = request.Properties.ContainsKey("Endpoint") ? (IEndpoint)request.Properties["Endpoint"] : null; if (endpoint?.RequireAuth == true || (authInfo != null)) { if (!request.Headers.Contains("Authorization")) { request.Headers.Add("Authorization", $"Bearer {authInfo.AccessToken}"); } } // Dispatch to on send listeners OnSend?.Invoke(this, request, endpoint); // HttpResponseMessage response = await base.SendAsync(request, cancellationToken); // Dispatch to on response listeners OnResponse?.Invoke(this, response, endpoint); return(response); }
public void Send(Message message) { message.Send = true; message.To.Messages.Add(message); message.To.NewMessage(message); OnSend?.Invoke(this, new OnSendEventArgs(message.ReadMessage(this), message.From.Username, message.To.Username)); }
private void SendCallBack(IAsyncResult asyncResult) { Socket socket = (Socket)asyncResult.AsyncState; socket.EndSend(asyncResult); OnSend?.Invoke(socket.RemoteEndPoint); }
private async void NewClient(Socket socket, int millisecondsDelay) { try { socket.Connect(address); OnConnect?.Invoke(this, new EventArgs()); } catch (Exception exception) { OnConnectException?.Invoke(this, new ExceptionEventArgs(socket, exception)); } while (true) { try { socket.Send(messageBuffer); OnSend?.Invoke(this, new EventArgs()); } catch (Exception exception) { OnSendException?.Invoke(this, new ExceptionEventArgs(socket, exception)); } await Task.Delay(millisecondsDelay); } }
// method send bijna volledig aangepast = Ondelivering kan invoke zijn als passedTime < totamTimeSendingInt is en OnSend als passedTime == totalTimeSendingInt private void Send() { // 10 "minutes" = 1 second Thread.Sleep(100); if (passedTime < totalTimeSendingInt) { passedTime++; } totalTimeSending = currentDelivery.TravelTime * currentDelivery.Factor; totalTimeSendingInt = Decimal.ToInt32(totalTimeSending); remainingTime = totalTimeSendingInt - passedTime; if (OnDelivering != null) { OnDelivering?.Invoke(this, new DeliveryEventArgs(passedTime, remainingTime, totalTimeSendingInt)); } if (passedTime == totalTimeSendingInt) { if (OnSend != null) { OnSend?.Invoke(this, new DeliveryEventArgs(passedTime, remainingTime, totalTimeSendingInt)); } } }
public void Update(int pendingPackets) { if (pendingPackets == 0) { OnSend?.Invoke(0, _memory); } }
private static IWebsocket CreateSocket() { bool open = false; bool closed = true; IWebsocket obj = Mock.Of <IWebsocket>(); var socket = Mock.Get(obj); socket.Setup(s => s.Close()).Returns(Task.FromResult(true)).Callback(() => { var closing = socket.Object.IsOpen; open = false; closed = true; if (closing) { socket.Raise(s => s.OnClose += null); } OnClose?.Invoke(socket); }); socket.Setup(s => s.IsOpen).Returns(() => open); socket.Setup(s => s.Send(It.IsAny <string>())).Callback(new Action <string>((data) => { OnSend?.Invoke(socket, data); })); socket.Setup(s => s.IsClosed).Returns(() => closed); socket.Setup(s => s.Connect()).Returns(Task.FromResult(true)).Callback(() => { socket.Setup(s => s.IsOpen).Returns(() => open); socket.Setup(s => s.IsClosed).Returns(() => closed); open = true; closed = false; socket.Raise(s => s.OnOpen += null); OnOpen?.Invoke(socket); }); return(socket.Object); }
/// <summary> /// Send a <see cref="NetObject"/>. /// </summary> /// <param name="netobj">The NetObject to send. Cannot be null.</param> /// <param name="socket">The client to send the data to.</param> /// <exception cref="NullReferenceException"></exception> public void Send(Socket socket, bool deleteOnSend = true) { if (socket == null) { return; } Task.Run(() => { Type type = this.GetType(); if (!_GenericConstructors.TryGetValue(type, out ConstructorInfo ctor)) { ctor = typeof(NetData <>).MakeGenericType(type).GetConstructor(new [] { type }); _GenericConstructors.TryAdd(type, ctor); } OnSend?.BeginInvoke(this, type, socket, null, null); ((ISendible)ctor.Invoke(new object[] { this })).Send(socket); if (deleteOnSend) { this.Delete(); } }); }
/// <summary> /// 将文件写到Socket /// </summary> /// <param name="s">要发送文件的Socket</param> /// <param name="strFile">要发送的文件</param> /// <returns>是否成功</returns> public static bool WriteFileToSocket(Socket s, string strFile, OnSend OnSendFile) { FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read, FileShare.Read); int iLen = (int)fs.Length; WriteDynamicLenToSocket(s, iLen); byte[] buf = new byte[iLen]; try { fs.Read(buf, 0, iLen); return(WriteBufToSocket(s, buf, 0, iLen, DEALLEN, OnSendFile)); } catch (Exception err) { MessageBox.Show("发送文件失败!" + err.Message); return(false); } finally { fs.Close(); } }
/// <summary> /// 设置回调函数 /// </summary> /// <param name="prepareConnect"></param> /// <param name="connect"></param> /// <param name="send"></param> /// <param name="recv"></param> /// <param name="close"></param> /// <param name="error"></param> public virtual void SetCallback(OnPrepareConnect prepareConnect, OnConnect connect, OnSend send, OnPullReceive recv, OnClose close, OnError error) { // 设置 Socket 监听器回调函数 SetOnPullReceiveCallback(recv); base.SetCallback(prepareConnect, connect, send, null, close, error); }
public static void Send <T>(T Event) where T : BaseEvent { if (EventList_.ContainsKey(Event.EventName)) { ((EventListenerImpl <T>)EventList_[Event.EventName]).Trigger(Event); OnSend?.Invoke(Event); } }
private void HandleOutput(long output) { _outputQueue.Enqueue(output); if (_outputQueue.Count == 3) { OnSend?.Invoke((int)_outputQueue.Dequeue(), new Packet(_outputQueue.Dequeue(), _outputQueue.Dequeue())); } }
/// <summary> /// Sends packet to the destination. /// </summary> public void Send(NetworkMessage msg) { if (OnSend != null) { OnSend.BeginInvoke(msg, null, null); } pipe.Write(msg.GetData(), 0, msg.Length); }
private void WorkThreadFunction() { while (true) { OnSpeed?.Invoke(this, Data.GetSpeed()); OnHeartRate?.Invoke(this, Data.GetHeartRate()); OnSend?.Invoke(this, 0); Thread.Sleep(1000); } }
public async Task SendAsync(IClient toClient, string message, IClient fromClient) { if (toClient.WebSocket.State != WebSocketState.Open) { return; } await toClient.WebSocket.SendAsync(message); OnSend?.Invoke(this, new SocketSentEventArgs(toClient, fromClient, message)); }
/// <summary> /// 发送回调 /// </summary> /// <param name="e">操作对象</param> private void ProcessSend(SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { return; } m_sendPool.Push(e); OnSend?.Invoke(e.RemoteEndPoint, e.BytesTransferred); }
// notify about new send telegram public virtual void NotifySend(Telegram tel) { try { OnSend?.Invoke(tel); } catch (Exception e) { Log.AddLog(Log.Severity.EXCEPTION, Name, nameof(NotifyRcv), e.Message); } }
protected override void Start() { base.Start(); _btnSend.onClick.AddListener(() => { OnSend?.Invoke(); }); _btnAlreadyAccount.onClick.AddListener(() => { OnAlreadyAccount?.Invoke(); }); }
private void SendCallBack(IAsyncResult asyncResult) { //Socket socket = (Socket)asyncResult.AsyncState; TCPConnection client = (TCPConnection)asyncResult.AsyncState; if (!client.Socket.Connected) { return; } client.Socket.EndSend(asyncResult); //if(OnSend != null) OnSend?.Invoke(client.Socket.RemoteEndPoint, responseData); }
public virtual void SetOnSendCallback(OnSend send) { if (send != null) { OnSendCallback = new OnSend(send); SDK_OnSendCallback = new HPSocketSdk.OnSend(SDK_OnSend); } else { OnSendCallback = null; SDK_OnSendCallback = null; } HPSocketSdk.HP_Set_FN_Client_OnSend(pListener, SDK_OnSendCallback); }
public void SendMessage(User sender, Message message) { if (this == sender) { Console.WriteLine("Нельзя отправить сообщение отправителю."); return; } message.Sender = sender; message.Reciver = this; message.SendTime = DateTime.Now; OnSend?.Invoke(this, message); OnRecive?.Invoke(this, message); }
private void SendCallback(IAsyncResult ar) { // Retrieve the callback from the state object. OnSend onSend = (OnSend)ar.AsyncState; try { // Complete sending the data to the remote device. int bytesSent = sock.EndSend(ar); onSend.Invoke(bytesSent); } catch (Exception e) { LogUtil.Error("ClientSocket.SendCallback: " + e.ToString()); onSend.Invoke(-1); } }
public async Task SendAsync(IClient toClient, string message, IClient fromClient) { try { if (toClient?.WebSocket == null || toClient.WebSocket.State != WebSocketState.Open) { return; } await toClient.WebSocket.SendAsync(message); OnSend?.Invoke(this, new SocketSentEventArgs(toClient, fromClient, message)); } catch (Exception e) { // most probable cause is a secondary thread disposing the client and the websocket before sending the message _logger.LogDebug($"Message to {toClient?.Id} from {fromClient?.Id} has not been sent: {e}"); } }
/////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// 设置回调函数 /// </summary> /// <param name="prepareConnect"></param> /// <param name="connect"></param> /// <param name="send"></param> /// <param name="recv"></param> /// <param name="close"></param> /// <param name="error"></param> public void SetCallback(OnPrepareConnect prepareConnect, OnConnect connect, OnSend send, OnReceive recv, OnClose close, OnError error) { if (IsSetCallback == true) { throw new Exception("已经调用过SetCallback()方法,如果您确定没手动调用过该方法,并想要手动设置各回调函数,请在构造该类构造函数中传false值,并再次调用该方法。"); } // 设置 Socket 监听器回调函数 SetOnPrepareConnectCallback(prepareConnect); SetOnConnectCallback(connect); SetOnSendCallback(send); SetOnReceiveCallback(recv); SetOnCloseCallback(close); SetOnErrorCallback(error); IsSetCallback = true; }
private void SendAsync(byte[] messageBuffer, bool useExceptionList) { byte[] messageBytes = Buffer.AddSplitter(messageBuffer, 0); try { Socket.Send(messageBytes); OnSend?.Invoke(this, new EventArgs()); } catch (Exception exception) { if (useExceptionList) { CheckException(exception); } else { OnSendException?.Invoke(this, new ExceptionEventArgs(Socket, exception)); } } }
/// <summary> /// Отправка сообщения /// </summary> public async Task Send(string sendingData) { if (curSocket.State != WebSocketState.Open) { return; } try { byte[] encoded = Encoding.UTF8.GetBytes(sendingData); await curSocket.SendAsync(new ArraySegment <byte>(encoded, 0, encoded.Length), WebSocketMessageType.Text, true, CancellationToken.None); OnSend?.Invoke(this, new SendEventArgs { Data = data.ToString() }); } catch (Exception ex) { Console.WriteLine(ex); } }
/// <summary> /// 将长度不固定文本发送到socket /// </summary> /// <param name="s">要发送文本的Socket</param> /// <param name="strText">要发送的文本</param> /// <param name="OnSendText">成功发送一部分文本后的回调函数</param> /// <param name="settextlen">得到文本长度的回调函数</param> /// <returns></returns> public static bool WriteDynamicTextToSocket(Socket s, string strText, OnSend OnSendText) { byte[] buf = Encoding.UTF8.GetBytes(strText); int iLen = buf.Length; try { WriteDynamicLenToSocket(s, iLen); return(WriteBufToSocket(s, buf, 0, iLen, DEALLEN, OnSendText)); } catch (Exception err) { MessageBox.Show("发送文本失败!" + err.Message); return(false); } }
private void SendNotification(JObject payload, string deviceToken, BarkMessage barkMessage) { if (apnsBroker == null) { return; } if (deviceToken.Length != DeviceTokenLength) { return; } try { // 队列发送一个通知 apnsBroker.QueueNotification(new ApnsNotification { DeviceToken = deviceToken,//这里的deviceToken是ios端获取后传递到数据库统一记录管理的,有效的Token才能保证推送成功 Payload = payload }); OnSend?.Invoke(this, new SendEventArgs(payload, deviceToken, barkMessage)); } catch (Exception) { } }
protected void SendHandler(ServerMsgEventArgs e) { OnSend?.Invoke(this, e); }
public static extern void HP_Set_FN_Server_OnSend(IntPtr pListener, OnSend fn);
public static extern void HP_Set_FN_Client_OnSend(IntPtr pListener, OnSend fn);