Example #1
0
        public void ReadCallback(IAsyncResult ar)
        {
            DoTry(() =>
            {
                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                SocketSession session = (SocketSession)ar.AsyncState;

                // Read data from the client socket.
                int bytesRead  = session.CurrentSocket.EndReceive(ar);
                byte[] inBytes = new byte[bytesRead];
                if (bytesRead > 0)
                {
                    Array.Copy(session.InBuffer, 0, inBytes, 0, bytesRead);
                    Packet packet = inBytes.ToPacket();

                    // Not all data received. Get more.
                    session.CurrentSocket.BeginReceive(
                        session.InBuffer, 0, Session.BUFFER_SIZE, 0,
                        new AsyncCallback(ReadCallback), session);

                    if (packet.Type != DataTypes.PacketType.None)
                    {
                        byte[] bytes = this.Append(packet);

                        if (bytes != null)
                        {
                            FireOnMessageReceivedSuccess(session, bytes);
                            if (_messages.Count > 0)
                            {
                                ProcessSend(_messages.Dequeue());
                            }
                        }
                        else
                        {
                            session.Send(new Packet(
                                             DataTypes.PacketType.None, new byte[] { 0 }));
                        }
                    }
                    else
                    {
                        session.Send(session.PopPacket());
                    }
                }
            });
        }