示例#1
0
        static Packet()
        {
            Fragment = Platform.CoreFragment?.GetPacketFragment() ?? throw Platform.FragmentException();

            Fragment.Process = args => OnProcess.SafeInvoke(args);
            Fragment.Send    = args => OnSend.SafeInvoke(args);
        }
示例#2
0
        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);
        }
示例#3
0
 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));
 }
示例#4
0
        private void SendCallBack(IAsyncResult asyncResult)
        {
            Socket socket = (Socket)asyncResult.AsyncState;

            socket.EndSend(asyncResult);
            OnSend?.Invoke(socket.RemoteEndPoint);
        }
示例#5
0
 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));
                }
            }
        }
示例#7
0
 public void Update(int pendingPackets)
 {
     if (pendingPackets == 0)
     {
         OnSend?.Invoke(0, _memory);
     }
 }
示例#8
0
        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);
        }
示例#9
0
        /// <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();
                }
            });
        }
示例#10
0
        /// <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();
            }
        }
示例#11
0
 /// <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);
 }
示例#12
0
 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);
     }
 }
示例#13
0
        private void HandleOutput(long output)
        {
            _outputQueue.Enqueue(output);

            if (_outputQueue.Count == 3)
            {
                OnSend?.Invoke((int)_outputQueue.Dequeue(), new Packet(_outputQueue.Dequeue(), _outputQueue.Dequeue()));
            }
        }
示例#14
0
        /// <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);
     }
 }
示例#16
0
        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));
        }
示例#17
0
        /// <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);
        }
示例#18
0
 // 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);
     }
 }
示例#19
0
        protected override void Start()
        {
            base.Start();

            _btnSend.onClick.AddListener(() =>
            {
                OnSend?.Invoke();
            });

            _btnAlreadyAccount.onClick.AddListener(() =>
            {
                OnAlreadyAccount?.Invoke();
            });
        }
示例#20
0
        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);
        }
示例#21
0
        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);
        }
示例#22
0
        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);
        }
示例#23
0
        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);
            }
        }
示例#24
0
        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}");
            }
        }
示例#25
0
        ///////////////////////////////////////////////////////////////////////////////////////

        /// <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;
        }
示例#26
0
 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));
         }
     }
 }
示例#27
0
        /// <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);
            }
        }
示例#28
0
        /// <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);
            }
        }
示例#29
0
 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) { }
 }
示例#30
0
 protected void SendHandler(ServerMsgEventArgs e)
 {
     OnSend?.Invoke(this, e);
 }
示例#31
0
文件: Sdk.cs 项目: yxdh/HP-Socket
 public static extern void HP_Set_FN_Server_OnSend(IntPtr pListener, OnSend fn);
示例#32
0
文件: Sdk.cs 项目: yxdh/HP-Socket
 public static extern void HP_Set_FN_Client_OnSend(IntPtr pListener, OnSend fn);