Example #1
0
 private void DoReceive(object sender, SocketEventArgs e)
 {
     try
     {
         MessageReader writer = new MessageReader(e.Data);
         var           head   = writer.ReadHead();
         if (head.Success)
         {
             SuccessCallback(writer, head);
         }
         else
         {
             FailCallback(head);
         }
     }
     catch (Exception ex)
     {
         new BaseLog().SaveLog(ex);
     }
     finally
     {
         if (client != null)
         {
             client.StopWait();
         }
     }
 }
Example #2
0
 private void socket_OnFailure(object sender, SocketEventArgs args)
 {
     if (ConnectionFailed != null)
     {
         ConnectionFailed(this, new SmppEventArgs());
     }
 }
Example #3
0
        private void Server_ReceiveCompleted(object sender, SocketEventArgs e)
        {
            var raw = Encoding.UTF8.GetString(e.Data);

            AppendText($"ReceiveComplete:{e.Socket.RemoteEndPoint.ToString()}\n{raw}");
            e.Socket.Send(Encoding.UTF8.GetBytes("cmd"));
        }
Example #4
0
File: Pipe.cs Project: nka1/Daytona
        private static void AddSubscriberCountChannelReceiveReady(object sender, SocketEventArgs e)
        {
            WritelineToLogFile("AddSubscriberCountChannelReceiveReady");
            var messageReceiver = new MessageReceiver();

            SubscriberCount = SubscriberCount + messageReceiver.ReceiveMessage((ZmqSocket)sender);
        }
Example #5
0
 private void ReadyToUpdateRoom(object Sender, SocketEventArgs E)
 {
     E.Socket.Send(Encoding.UTF8.GetBytes("ReadyToReceive"));
     E.Socket["ReadyToReceive"] = null;
     E.Socket.ReceiveCompleted -= ReadyToUpdateRoom;
     E.Socket.ReceiveCompleted += BeginUpdateRoom;
 }
Example #6
0
        private void Socket_ReceiveMessageCompleted(object sender, SocketEventArgs e)
        {
            var call = GpcCall.Parser.ParseFrom(e.Data);

            if (!MethodsDic.ContainsKey(call.Method))
            {
                return;
            }
            var cb = MethodsDic[call.Method];

            if (cb.Param == null)
            {
                return;
            }
            var mMsg = Activator.CreateInstance(cb.Param, null);

            if (!(mMsg is IMessage))
            {
                return;
            }
            (mMsg as IMessage).MergeFrom(call.Params);
            if (cb.InvokedMethod != null)
            {
                cb.InvokedMethod(mMsg as IMessage);
            }
        }
Example #7
0
        private void SocketClientDisconnected(object sender, SocketEventArgs e)
        {
            var message = "The client has disconnected from the server";

            WriteToTextBox(txtStatusLog, message);
            EnableDisableButtonControls(true);
        }
Example #8
0
 private void ServerAccepted(object Sender, SocketEventArgs E)
 {
     MessageBox.Show("连接成功。", "来自" + E.Socket["RemoteEndPoint"] + "的信息",
                     MessageBoxButton.OK, MessageBoxImage.Information);
     E.Socket.Send(CurrentRoom);
     E.Socket.ReceiveCompleted += LetInReceived;
 }
Example #9
0
            private void SocketListener_DataReceived(object sender, SocketEventArgs e)
            {
                var connection = (TcpConnection)e.Socket.UserToken;
                var message    = serializer.Deserialize(e.Data);

                dispatcher.Dispatch(connection, message);
            }
Example #10
0
            private void SocketClient_Disconnected(object sender, SocketEventArgs e)
            {
                var newClient = (TcpClient)sender;

                newClient.DataReceived -= new EventHandler <SocketEventArgs>(SocketClient_DataReceived);
                newClient.Disconnected -= new EventHandler <SocketEventArgs>(SocketClient_Disconnected);
            }
Example #11
0
 private void ClientConnected(object sender, SocketEventArgs e)
 {
     ConnectButton.Invoke(new Action(() =>
     {
         ConnectButton.Enabled = false;
     }));
 }
 private Task SocketOpened(DiscordClient shard, SocketEventArgs _)
 {
     // We do nothing else here, since this kinda doesn't mean *much*? It's only really started once we get Ready/Resumed
     // And it doesn't get fired first time around since we don't have time to add the event listener before it's fired'
     _logger.Information("Shard #{Shard} opened socket", shard.ShardId);
     return(Task.CompletedTask);
 }
Example #13
0
        private void Socket_Connected(object sender, SocketEventArgs e)
        {
            var socket = (TcpClient)sender;

            socket.DataReceived += new EventHandler <SocketEventArgs>(Socket_DataReceived);
            socket.Disconnected += new EventHandler <SocketEventArgs>(Socket_Disconnected);
        }
Example #14
0
 internal override void FireEvent(object sender, SocketEventArgs e)
 {
     if (OnNewActivity != null)
     {
         OnNewActivity(sender, e);
     }
 }
        private void SocketListener_Disconnected(object sender, SocketEventArgs e)
        {
            var connection = (InboundConnection)e.Socket.UserToken;

            connections.TryRemove(connection.Guid, out InboundConnection _);
            connection.Disconnected(e.SocketError != SocketError.Success);
        }
Example #16
0
        private GameSession GetSession(SocketEventArgs e, RequestPackage package)
        {
            //使用代理分发器时,每个ssid建立一个游服Serssion
            GameSession session;

            if (package.ProxySid != Guid.Empty)
            {
                session = GameSession.Get(package.ProxySid) ??
                          (package.IsProxyRequest
                              ? GameSession.Get(e.Socket.HashCode)
                              : GameSession.CreateNew(package.ProxySid, e.Socket, _socketRoom));
                if (session != null)
                {
                    session.ProxySid = package.ProxySid;
                }
            }
            else
            {
                session = GameSession.Get(package.SessionId) ?? GameSession.Get(e.Socket.HashCode);
            }
            if (session == null)
            {
                session = GameSession.CreateNew(e.Socket.HashCode, e.Socket, _socketRoom);
            }
            if ((!session.Connected || !Equals(session.RemoteAddress, e.Socket.RemoteEndPoint.ToString())))
            {
                GameSession.Recover(session, e.Socket.HashCode, e.Socket, _socketRoom);
            }
            return(session);
        }
        private void SocketListener_DataRecieved(object sender, SocketEventArgs e)
        {
            var connection = (Connection)e.Socket.UserToken;
            var message    = messageSerializer.Deserialize(e.Data);

            connection.ReceiveMessage(message);
        }
Example #18
0
 private void OnDataReceived(SocketEventArgs e)
 {
     if (DataReceived != null)
     {
         DataReceived(this, e);
     }
 }
Example #19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="exSocket"></param>
 /// <param name="opCode"></param>
 /// <param name="reason"></param>
 protected void Dispose(TNSocket exSocket, sbyte opCode, string reason)
 {
     try
     {
         var e = new SocketEventArgs()
         {
             Socket = exSocket,
             Source = new DataMessage()
             {
                 OpCode = opCode, Message = reason
             }
         };
         DoClosed(e);
         OnDisconnected(e);
         if (exSocket != null)
         {
             exSocket.Close();
         }
         sendEventArg.Dispose();
         receiveEventArg.Dispose();
         receiveWaitEvent.Dispose();
         socketClient.Dispose();
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("Dispose connect of client error:{0}", ex);
     }
 }
Example #20
0
        void SocketListen_Connected(object sender, SocketEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                return;
            }

            try
            {
                var command  = _cmdFactory.Invoke();
                var session  = new ClientSessionImpl(_socketListen, _hostContext, e.Socket, command);
                var listener = _appListener.LoggedIn(session);
                if (listener == null)
                {
                    session.Close();
                    return;
                }

                _kvListener[session.Guid] = listener;
                SessionContext.Session    = session;
                try
                {
                    RaiseNewerSessionEvent(new SessionEventArgs(session));
                }
                finally
                {
                    SessionContext.Session = null;
                }
            }
            catch (Exception ex)
            {
                logger.Error("ServiceHost Connected error:{0}", ex);
            }
        }
Example #21
0
        private void Listener_ReceiveCompleted(object sender, SocketEventArgs e)
        {
            e.Socket.SendAsync(Encoding.UTF8.GetBytes(e.Socket.RemoteEndPoint.ToString()));
            myde md = new myde(settextbox);

            this.BeginInvoke(md, e.Data);
        }
Example #22
0
        private void socket_SendCompleted(object sender, SocketEventArgs e)
        {
            if (!SendCache.ContainsKey(e.Data))
            {
                return;
            }
            CommunicationSendEventArgs eventArgs = SendCache[e.Data];

            SendCache.Remove(e.Data);
            byte[] data = null;
            if (e.Data[0] == 5)
            {
                int offset = SendMark[eventArgs];
                if (offset < eventArgs.Data.Length)
                {
                    data = GetSendBlock(eventArgs, offset);
                    SendCache.Add(data, eventArgs);
                    SendMark[eventArgs] = offset + data.Length - 21;
                    Socket.SendAsync(data);
                }
                else
                {
                    SendMark.Remove(eventArgs);
                    if (SendCompleted != null)
                    {
                        SendCompleted(this, eventArgs);
                    }
                }
            }
        }
 private void client_DisconnectCompleted(object sender, SocketEventArgs e)
 {
     if (_Connecting)
     {
         _Connecting = false;
     }
 }
Example #24
0
        /// <summary>
        /// This method is invoked when a new inbound socket hits our server.  We will create a new
        /// SMPP session object to manage the socket and begin communicating with the ESME session.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected void OnStartSession(object sender, SocketEventArgs args)
        {
            ConnectEventArgs connEv = (ConnectEventArgs)args;
            SocketClient     scNew  = connEv.Client;

            // Create a new SMPP session to manage this connection.
            SmscSession newSession = new SmscSession(this, scNew, systemid_);

            // Back-link the session
            scNew.Tag = newSession;

            // Notify anyone who wants to know
            SmppConnectEventArgs sce = new SmppConnectEventArgs(scNew.Address, newSession);

            if (OnNewSession != null)
            {
                OnNewSession(this, sce);
            }
            if (!sce.AllowConnection)
            {
                scNew.Close(true);
            }
            else
            {
                scNew.OnEndSession += OnEndClientSession;
                lock (clients_)
                {
                    clients_.Add(newSession);
                }
            }
        }
Example #25
0
        void DataReceived(object sender, SocketEventArgs e)
        {
            var bytes = new byte[16];

            Buffer.BlockCopy(e.Data, 0, bytes, 0, 16);
            var ssid       = new Guid(bytes);
            var data       = e.Data;
            var sendResult = proxy.SendDataBack(ssid, e.Data, 16, e.Data.Length - 16);

            if (!sendResult)
            {
                Task.Factory.StartNew(() =>
                {
                    NameValueCollection requestParam = new NameValueCollection();
                    requestParam["actionid"]         = "2";
                    requestParam["ssid"]             = ssid.ToString("N");
                    requestParam["msgid"]            = "0";

                    byte[] paramData = Encoding.ASCII.GetBytes(RequestParse.ToQueryString(requestParam));

                    try
                    {
                        Send(paramData);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("发送tcp连接断开通知失败。", ex);
                    }
                });
            }
        }
Example #26
0
        public void MessageReceived(object Sender, SocketEventArgs E)
        {
            string Data = Encoding.UTF8.GetString(E.Data);

            string[] Fragments = Data.Split(new[] { "|*|" },
                                            StringSplitOptions.RemoveEmptyEntries);
            if (Fragments[0] != "ChatMessage")
            {
                return;
            }

            Player Speaker = Fragments[1] == "System" ? null : CurrentRoom.Members
                             .Find(O => O.Id == Guid.Parse(Fragments[1]));

            this.Dispatcher.Invoke(() =>
                                   SendMessageAlone(Fragments[2], Speaker,
                                                    Speaker != null && CurrentRoom.IsHost(Speaker)));

            if (CurrentRoom.IsHost(App.CurrentUser))
            {
                var From = E.Socket["User"] as User;
                foreach (var Client in App.Server
                         .Where(Client => !From.Equals(Client["User"])))
                {
                    Client.SendAsync(E.Data);
                }
            }
        }
        /// <summary>
        /// Receive data event listener
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void ReceiveData(object sender, SocketEventArgs args)
        {
            if (args.Socket.Available > 0)
            {
                string buffer = await ReadToBuffer(args.Socket);

                if (buffer != "")
                {
                    // Sometimes two messages have been sent before the buffer is read, so we split it
                    string[] bursts = buffer.Split((char)4);
                    foreach (string singleBurst in bursts)
                    {
                        try
                        {
                            string[] tuple   = singleBurst.Split(new string[] { "\a\a\a" }, StringSplitOptions.None);
                            string   command = tuple[0];
                            string   obj     = tuple[1];
                            if (command != "PING")
                            {
                                ProcessData(command, obj);
                            }
                        }
                        catch { /* If only half of the next message was received this will be triggered, however no action is required */ }
                    }
                }
            }
        }
Example #28
0
 private void OnDisconnected(SocketEventArgs e)
 {
     if (Disconnected != null)
     {
         Disconnected(this, e);
     }
 }
Example #29
0
        /// <summary>
        /// Method executed by the client listening thread
        /// </summary>
        /// <param name="threadArgs">An object encapsulating the server node connection</param>
        private void MessageListenerAction(object threadArgs)
        {
            INetworkNode senderNode = (INetworkNode)threadArgs;
            Socket       socket     = senderNode.Socket;

            socket.ReceiveBufferSize = ReceiveBufferSize;
            if (ReceiveTimeOut > 0)
            {
                socket.ReceiveTimeout = ReceiveTimeOut;
            }

            while (true)
            {
                byte[] buffer   = new byte[socket.ReceiveBufferSize];
                int    received = socket.Receive(buffer);
                if (received > 0)
                {
                    if (OnReceivedStreamMessage != null)
                    {
                        SocketEventArgs args = new SocketEventArgs(buffer.Take(received).ToArray(), senderNode);
                        OnReceivedStreamMessage(socket, args);
                    }
                }
                else
                {
                    //timed out
                    socket.Disconnect(false);
                    break;
                }
            }
        }
Example #30
0
 internal override void FireEvent(object sender, SocketEventArgs e)
 {
     if (OnNewQuestion != null)
     {
         OnNewQuestion(sender, e);
     }
 }
 /// <summary>
 /// Forwards requests from the frontend socket to the backend socket.
 /// </summary>
 /// <param name="args">A <see cref="SocketEventArgs"/> object containing the poll event args.</param>
 protected override void FrontendHandler(SocketEventArgs args)
 {
     FrontendSocket.Forward(BackendSocket);
 }
Example #32
0
 /// <summary>
 /// Invoked when a message has been received by the backend socket.
 /// </summary>
 /// <param name="args">A <see cref="SocketEventArgs"/> object containing the poll event args.</param>
 protected abstract void BackendHandler(SocketEventArgs args);
Example #33
0
 private void OnNetworkEvent(byte[] data, SocketEventArgs e)
 {
     switch (e.socketEvent)
     {
         case SocketEventArgs.SocketEventType.ACCEPT:
             OnNetPlayerConnected(e.endpoint);
             break;
         case SocketEventArgs.SocketEventType.READ:
             OnNetPlayerData(e.endpoint, DataUtils.FromBytes<TankBattleCommand>(data));
             break;
         case SocketEventArgs.SocketEventType.DROP:
             OnNetPlayerDisconnected(e.endpoint);
             break;
     }
 }
        /// <summary>
        /// Event handler for Http2 data.
        /// </summary>
        /// <param name="sender">The sender object.</param>
        /// <param name="e">Event arguments.</param>
        private void OnSocketData(object sender, SocketEventArgs e)
        {
            try
            {
                BaseFrame frame = this.serializer.Deserialize(e.BinaryData);

                if (this.OnFrameReceived != null)
                {
                    this.OnFrameReceived(this, new FrameEventArgs(frame));
                }
                try
                {
                    if (frame is DataFrame)
                    {
                        this.ProcessDataFrame((DataFrame)frame);
                    }
                    else if (frame is ControlFrame)
                    {
                        this.ProcessControlFrame((ControlFrame)frame);
                    }
                    else
                    {
                        throw new InvalidOperationException("Unsupported frame type");
                    }
                }
                catch (Exception streamError)
                {
                    if (streamError is ProtocolExeption || this.OnStreamError == null)
                    {
                        throw;
                    }

                    this.OnStreamError(this, new StreamErrorEventArgs(this.streamsStore.GetStreamById(frame.StreamId), streamError));
                }
            }
            catch (Exception protocolError)
            {
                if (this.OnError != null)
                {
                    this.OnError(this, new ProtocolErrorEventArgs(protocolError));
                }
            }
        }
Example #35
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="e"></param>
 protected virtual void TriggerError(SocketEventArgs e)
 {
     SocketEventHandler handler = OnError;
     if (handler != null) handler(this, e);
 }
Example #36
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="e"></param>
 protected void TriggerMessage(SocketEventArgs e)
 {
     SocketEventHandler handler = OnMessage;
     if (handler != null) handler(this, e);
 }
Example #37
0
        void ClientWebSocket_DataReceived(ClientSocket sender, SocketEventArgs e)
        {
            try
            {
                if (e.Source.OpCode == OpCode.Ping)
                {
                    DoPing(e);
                }
                else if (e.Source.OpCode == OpCode.Pong)
                {
                    DoPong(e);
                }
                else
                {
                    TriggerMessage(e);
                }

            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// Processes the messages.
        /// </summary>
        /// <param name="stateInfo">The state info.</param>
        private void ProcessMessages(Object stateInfo)
        {
            do
            {
                byte[] data = ReceiveData();

                SocketEventArgs args = new SocketEventArgs(data);
                OnSocketData(this, args);
            }
            while (this.opened);
        }
Example #39
0
    /// <summary>Called when a client connects to the http server</summary>
    /// <param name="sender">The socket listener reporting the new connection</param>
    /// <param name="arguments">Contains the socket of the connecting client</param>
    private void clientConnected(object sender, SocketEventArgs arguments) {
      ClientConnection clientConnection;

      // An exception from the AcceptClientConnection method would end up in the
      // ThreadPool. In .NET 2.0, the behavior in this case is clearly defined
      // (ThreadPool prints exception to console and ignores it), but since this
      // would leave the client running into the timeout, we try to at least
      // shut down the socket gracefully and to pester the developer
      try {
        clientConnection = AcceptClientConnection(arguments.Socket);
      }
      catch(Exception exception) {
        System.Diagnostics.Trace.WriteLine(
          "AcceptClientConnection() threw an exception, dropping connection"
        );
        System.Diagnostics.Trace.WriteLine(
          "Exception from AcceptClientConnection(): " + exception.ToString()
        );
        System.Diagnostics.Trace.Assert(
          false, "AcceptClientConnection() threw an exception, connection will be dropped"
        );

        // Send 500 internal server error here!

        try {
          arguments.Socket.Shutdown(SocketShutdown.Both);
        }
        finally {
          arguments.Socket.Close();
        }

        throw;
      }

      try {
        ConnectionEntry entry = new ConnectionEntry(clientConnection);
        lock(this.clientCleanupQueue) {
          this.clientCleanupQueue.Enqueue(DateTime.UtcNow, entry);
        }
        lock(this.connectedClients) {
          this.connectedClients.Add(clientConnection, entry);
        }
      }
      catch(Exception) {
        clientConnection.Drop();
        throw;
      }
    }
Example #40
0
 private void DoPong(SocketEventArgs e)
 {
     SocketEventHandler handler = OnPong;
     if (handler != null) handler(this, e);
 }
Example #41
0
        private void SocketErrorHandler(object sender, SocketEventArgs e)
        {
            rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
            PeerFinder_AdvertiseButton.Visibility = Visibility.Visible;
            PeerFinder_StopAdvertiseButton.Visibility = Visibility.Collapsed;
            PeerFinder_AdvertiseGrid.Visibility = Visibility.Visible;

            // Browse and DiscoveryData controls are valid for Browse support
            if (_browseConnectSupported)
            {
                PeerFinder_BrowseGrid.Visibility = Visibility.Visible;
            }
            PeerFinder_ConnectionGrid.Visibility = Visibility.Collapsed;

            // Clear the SendToPeerList
            PeerFinder_SendToPeerList.Visibility = Visibility.Collapsed;
            PeerFinder_SendToPeerList.Items.Clear();

            _socketHelper.CloseSocket();
        }
Example #42
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="e"></param>
 protected override void DoOpened(SocketEventArgs e)
 {
     TriggerOpened(e);
     base.DoOpened(e);
 }
Example #43
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="e"></param>
 protected override void DoClosed(SocketEventArgs e)
 {
     TriggerClosed(e);
     base.DoClosed(e);
 }
 /// <summary>
 /// Not implemented for the <see cref="ForwarderDevice"/>.
 /// </summary>
 /// <param name="args">A <see cref="SocketEventArgs"/> object containing the poll event args.</param>
 protected override void BackendHandler(SocketEventArgs args)
 {
 }
Example #45
0
 private void DoDisconnected(object sender, SocketEventArgs e)
 {
     DoError("服务器已关闭");
 }
Example #46
0
 void SocketConnected(object sender, SocketEventArgs e)
 {
     Interlocked.Increment(ref connections);
     ServerInstrumentation.Current.Connect();
     SocketAsyncEventArgs args = socketArgsPool.CheckOut();
     bufferManager.CheckOut(args);
     var connection = new ServerConnection(e.Socket, args,
         new DataReceivedCallback(DataReceived),
         new DisconnectedCallback(Disconnected));
 }
Example #47
0
        private void DoReceive(object sender, SocketEventArgs e)
        {
            try
            {

                MessageReader writer = new MessageReader(e.Data);
                var head = writer.ReadHead();
                if (head.Success)
                {
                    SuccessCallback(writer, head);
                }
                else
                {
                    FailCallback(head);
                }
            }
            catch (Exception ex)
            {
                new BaseLog().SaveLog(ex);
            }
            finally
            {
                if (client != null)
                    client.StopWait();
            }
        }
Example #48
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="e"></param>
 protected void TriggerClosed(SocketEventArgs e)
 {
     SocketEventHandler handler = OnClosed;
     if (handler != null) handler(this, e);
 }
Example #49
0
 public SocketEvent(SocketEventArgs e, byte[] d)
 {
     eventArgs = e;
     data = d;
 }