Exemple #1
0
 public void SendUnencoded(string text, Action<Exception> callback = null)
 {
     byte[] writeBuffer = Encoding.GetBytes(text);
     NetworkStream netstream = _tcp.GetStream();
     var state = new SendState(netstream, callback);
     netstream.BeginWrite(writeBuffer, 0, writeBuffer.Length, SendCallback, state);
 }
Exemple #2
0
 public void Send(string text, Action<Exception> callback = null)
 {
     Debug.WriteLine(text);
     byte[] writeBuffer = EncodeServerData(text);
     NetworkStream netstream = _tcp.GetStream();
     var state = new SendState(netstream, callback);
     netstream.BeginWrite(writeBuffer, 0, writeBuffer.Length, SendCallback, state);
 }
        public void SendPacket(Packet pkt)
        {
            pendingPackets.Enqueue(pkt);
            if (CanSendPacket(send, false))
            {
                var dat = (send.UserToken as SendToken).Packet.Write(parent);

                sendState = SendState.Sending;
                send.SetBuffer(dat, 0, dat.Length);
                if (!skt.SendAsync(send))
                    IOCompleted(this, send);
            }
        }
Exemple #4
0
        private void serialData(string s)
        {
            txtLog.AppendText(s);

            string[] sLines = s.Split(new char[]{'\n'}, StringSplitOptions.RemoveEmptyEntries);
            foreach (string sLine in sLines)
            {
                bool isOk = sLine.StartsWith("200 OK ");
                if (_sendState == SendState.WAITFORSEND && isOk)
                    _sendState = SendState.SENDINGFILE;
                if (_sendState == SendState.SENDINGFILE && isOk)
                {
                    NextFile();
                    return;
                }
            }
        }
Exemple #5
0
        void IConnectionAdapter.Send(Frame frame)
        {
            SendState state;

            if (_closing || _disposed)
                return;

            state = new SendState();
            state.data = frame.ToBytes();

            if (_sending)
            {
                _sendQueue.Enqueue(state);
                return;
            }

            processSendState(state);
        }
Exemple #6
0
 public void AddtoSend(byte[] inData, byte inLen)
 {
     Console.WriteLine("_crtSendState:" + _crtSendState);
     if (_crtSendState != SendState.IDEL)
     {
         //throw new Exception("Com not ready!!");
     }
     else
     {
         _crtSendState = SendState.SENDING;
         byte[] sendbuf = Packet2Cmd(inData, inLen);
         _CrtSendBuf = sendbuf.ToList();
         _InData.Clear();
         PrintCmd(sendbuf);
         Sendcmd(sendbuf, sendbuf.Length);
         _crtSendState = SendState.RECEIVEING;
         tmr.Start();
     }
 }
Exemple #7
0
 private void NextFile()
 {
     _sendState = SendState.NONE;
     if (_workQueue.Count == 0)
         DumpFileTable();
     else
     {
         SendOneFile(_workQueue[0].FullName);
         _workQueue.RemoveAt(0);
     }
 }
        /// <summary>
        /// Callback method for asynchronous connect operation.
        /// </summary>
        private void ProcessConnect(ConnectState connectState)
        {
            ReceiveState receiveState = null;
            SendState sendState = null;

            try
            {
                // Quit if this connection loop has been cancelled
                if (connectState.Token.Cancelled)
                    return;

                // Increment the number of connection attempts that
                // have occurred in this asynchronous connection loop
                connectState.ConnectionAttempts++;

                // Check the SocketAsyncEventArgs for errors during the asynchronous connection attempt
                if (connectState.ConnectArgs.SocketError != SocketError.Success)
                    throw new SocketException((int)connectState.ConnectArgs.SocketError);

                // Set the size of the buffer used by the socket to store incoming data from the server
                connectState.Socket.ReceiveBufferSize = ReceiveBufferSize;

                if (m_integratedSecurity)
                {
#if !MONO
                    // Check the state of cancellation one more time before
                    // proceeding to the next step of the connection loop
                    if (connectState.Token.Cancelled)
                        return;

                    // Create the SslStream object used to perform
                    // send and receive operations on the socket
                    connectState.NetworkStream = new NetworkStream(connectState.Socket, false);
                    connectState.NegotiateStream = new NegotiateStream(connectState.NetworkStream, true);
                    connectState.NegotiateStream.BeginAuthenticateAsClient(m_networkCredential ?? (NetworkCredential)CredentialCache.DefaultCredentials, string.Empty, ProcessIntegratedSecurityAuthentication, connectState);
#endif
                }
                else
                {
                    // Initialize the SocketAsyncEventArgs for receive operations
                    connectState.ReceiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                    connectState.ReceiveArgs.SetBuffer(new byte[ReceiveBufferSize], 0, ReceiveBufferSize);

                    if (m_payloadAware)
                        connectState.ReceiveArgs.Completed += (sender, args) => ProcessReceivePayloadAware((ReceiveState)args.UserToken);
                    else
                        connectState.ReceiveArgs.Completed += (sender, args) => ProcessReceivePayloadUnaware((ReceiveState)args.UserToken);

                    // Initialize the SocketAsyncEventArgs for send operations
                    connectState.SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                    connectState.SendArgs.SetBuffer(new byte[SendBufferSize], 0, SendBufferSize);
                    connectState.SendArgs.Completed += (sender, args) => ProcessSend((SendState)args.UserToken);

                    // Initialize state object for the asynchronous send loop
                    sendState = new SendState();
                    sendState.Token = connectState.Token;
                    sendState.Socket = connectState.Socket;
                    sendState.ReceiveArgs = connectState.ReceiveArgs;
                    sendState.SendArgs = connectState.SendArgs;
                    sendState.SendArgs.UserToken = sendState;

                    // Store sendState in m_sendState so that calls to Disconnect
                    // and Dispose can dispose resources and cancel asynchronous loops
                    m_sendState = sendState;

                    // Check the state of cancellation one more time before
                    // proceeding to the next step of the connection loop
                    if (connectState.Token.Cancelled)
                        return;

                    // Notify of established connection
                    m_connectWaitHandle.Set();
                    OnConnectionEstablished();

                    // Initialize state object for the asynchronous receive loop
                    receiveState = new ReceiveState();
                    receiveState.Token = connectState.Token;
                    receiveState.Socket = connectState.Socket;
                    receiveState.Buffer = connectState.ReceiveArgs.Buffer;
                    receiveState.ReceiveArgs = connectState.ReceiveArgs;
                    receiveState.ReceiveArgs.UserToken = receiveState;
                    receiveState.SendArgs = connectState.SendArgs;

                    // Store receiveState in m_receiveState so that calls to Disconnect
                    // and Dispose can dispose resources and cancel asynchronous loops
                    m_receiveState = receiveState;

                    // Start receiving data
                    if (m_payloadAware)
                        ReceivePayloadAwareAsync(receiveState);
                    else
                        ReceivePayloadUnawareAsync(receiveState);

                    // Further socket interactions are handled through the ReceiveArgs
                    // and SendArgs objects, so the ConnectArgs is no longer needed
                    connectState.ConnectArgs.Dispose();
                }
            }
            catch (SocketException ex)
            {
                // Log exception during connection attempt
                OnConnectionException(ex);

                // If the connection is refused by the server,
                // keep trying until we reach our maximum connection attempts
                if (ex.SocketErrorCode == SocketError.ConnectionRefused &&
                    (MaxConnectionAttempts == -1 || connectState.ConnectionAttempts < MaxConnectionAttempts))
                {
                    // Server is unavailable, so keep retrying connection to the server.
                    try
                    {
                        ConnectAsync(connectState);
                    }
                    catch
                    {
                        TerminateConnection(connectState.Token);
                    }
                }
                else
                {
                    // For any other reason, clean-up as if the client was disconnected.
                    TerminateConnection(connectState.Token);
                }
            }
            catch (Exception ex)
            {
                // Log exception during connection attempt
                OnConnectionException(ex);

                // Terminate the connection
                TerminateConnection(connectState.Token);
            }
            finally
            {
                // If the operation was cancelled during execution,
                // make sure to dispose of erroneously allocated resources
                if ((object)connectState != null && connectState.Token.Cancelled)
                    connectState.Dispose();

                if ((object)receiveState != null && receiveState.Token.Cancelled)
                    receiveState.Dispose();

                if ((object)sendState != null && sendState.Token.Cancelled)
                    sendState.Dispose();
            }
        }
Exemple #9
0
        internal override async ValueTask WriteAsync(ReadOnlyMemory <byte> buffer, bool endStream, CancellationToken cancellationToken = default)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }

            ThrowIfDisposed();

            if (!_canWrite)
            {
                throw new InvalidOperationException("Writing is not allowed on stream.");
            }

            lock (_sync)
            {
                if (_sendState == SendState.Aborted)
                {
                    throw new OperationCanceledException("Sending has already been aborted on the stream");
                }
            }

            using CancellationTokenRegistration registration = cancellationToken.Register(() =>
            {
                bool shouldComplete = false;
                lock (_sync)
                {
                    if (_sendState == SendState.None)
                    {
                        _sendState     = SendState.Aborted;
                        shouldComplete = true;
                    }
                }

                if (shouldComplete)
                {
                    _sendResettableCompletionSource.CompleteException(new OperationCanceledException("Write was canceled"));
                }
            });

            // Implicit start on first write.
            if (_started == StartState.None)
            {
                _started = StartState.Started;
                await StartWritesAsync();
            }

            await SendAsync(buffer, endStream?QUIC_SEND_FLAG.FIN : QUIC_SEND_FLAG.NONE);

            lock (_sync)
            {
                if (_sendState == SendState.Finished)
                {
                    _sendState = SendState.None;
                }
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Exit(this);
            }
        }
        private void SendCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                if (!skt.Connected) return;

                int len;
                switch (sendState)
                {
                    case SendState.Ready:
                        len = (e.UserToken as SendToken).Packet.Write(parent, sendBuff, 0);

                        sendState = SendState.Sending;
                        e.SetBuffer(0, len);

                        if (!skt.Connected) return;
                        skt.SendAsync(e);
                        break;
                    case SendState.Sending:
                        (e.UserToken as SendToken).Packet = null;

                        if (CanSendPacket(e, true))
                        {
                            len = (e.UserToken as SendToken).Packet.Write(parent, sendBuff, 0);

                            sendState = SendState.Sending;
                            e.SetBuffer(0, len);

                            if (!skt.Connected) return;
                            skt.SendAsync(e);
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
        /// <summary>
        /// Callback method for asynchronous send operation.
        /// </summary>
        private void ProcessSend(SendState sendState)
        {
            TcpClientPayload payload;
            ManualResetEvent handle = null;

            try
            {
                // Get the payload and its wait handle.
                payload = sendState.Payload;
                handle = payload.WaitHandle;

                // Quit if this send loop has been cancelled
                if (sendState.Token.Cancelled)
                    return;

                // Determine if the server disconnected gracefully
                if (!sendState.Socket.Connected)
                    throw new SocketException((int)SocketError.Disconnecting);

                // Check for errors during send operation
                if (sendState.SendArgs.SocketError != SocketError.Success)
                    throw new SocketException((int)sendState.SendArgs.SocketError);

                try
                {
                    // Set the wait handle to indicate
                    // the send operation has finished
                    handle.Set();
                }
                catch (ObjectDisposedException)
                {
                    // Ignore if the consumer has
                    // disposed of the wait handle
                }

                // Update statistics and notify that the send operation is complete
                UpdateBytesSent(sendState.SendArgs.BytesTransferred);
                OnSendDataComplete();
            }
            catch (ObjectDisposedException)
            {
                // Make sure connection is terminated when client is disposed
                TerminateConnection(sendState.Token);
            }
            catch (SocketException ex)
            {
                // Log exception during send operation
                OnSendDataException(ex);

                // Terminate connection when socket exception is encountered
                TerminateConnection(sendState.Token);
            }
            catch (Exception ex)
            {
                // For any other exception, notify and resume
                OnSendDataException(ex);
            }
            finally
            {
                // If the operation was cancelled during execution,
                // make sure to dispose of allocated resources
                if ((object)sendState != null && sendState.Token.Cancelled)
                    sendState.Dispose();

                try
                {
                    // Make sure to set the wait handle
                    // even if an exception occurs
                    if ((object)handle != null)
                        handle.Set();
                }
                catch (ObjectDisposedException)
                {
                    // Ignore if the consumer has
                    // disposed of the wait handle
                }

                // Attempt to send the next payload
                SendPayloadAsync(sendState);
            }
        }
Exemple #12
0
        public void SendPacket(Packet pkt)
        {
            try
            {
                pendingPackets.Enqueue(pkt);
                if (CanSendPacket(send, false))
                {
                    var dat = (send.UserToken as SendToken).Packet.Write(parent);

                    sendState = SendState.Sending;
                    send.SetBuffer(dat, 0, dat.Length);
                    if (!skt.SendAsync(send))
                        IOCompleted(this, send);
                }
            }
            catch
            {
                logger.Error("Error sending packet with ID " + pkt.ID.ToString());
            }
        }
        public void SendPacket(Packet pkt)
        {
            if (!skt.Connected) return;
            pendingPackets.Enqueue(pkt);
            if (CanSendPacket(send, false))
            {
                int len = (send.UserToken as SendToken).Packet.Write(parent, sendBuff, 0);

                sendState = SendState.Sending;
                send.SetBuffer(sendBuff, 0, len);
                if (!skt.SendAsync(send))
                    SendCompleted(this, send);
            }
        }
Exemple #14
0
        private void Handle(Action action, SocketError socketError, int bytesTransferred)
        {
            switch (m_state)
            {
                case State.Closed:
                    switch (action)
                    {
                        case Action.Start:
                            if (m_options.RawSocket)
                            {
                                m_encoder = new RawEncoder(Config.OutBatchSize, m_session, m_options.Endian);
                                m_decoder = new RawDecoder(Config.InBatchSize, m_options.MaxMessageSize, m_session, m_options.Endian);

                                Activate();
                            }
                            else
                            {
                                m_state = State.Handshaking;
                                m_handshakeState = HandshakeState.Closed;
                                HandleHandshake(action, socketError, bytesTransferred);
                            }

                            break;
                    }
                    break;
                case State.Handshaking:
                    HandleHandshake(action, socketError, bytesTransferred);
                    break;
                case State.Active:
                    switch (action)
                    {
                        case Action.InCompleted:
                            m_insize = EndRead(socketError, bytesTransferred);

                            ProcessInput();
                            break;
                        case Action.ActivateIn:

                            // if we stuck let's continue, other than that nothing to do
                            if (m_receivingState == ReceiveState.Stuck)
                            {
                                m_receivingState = ReceiveState.Active;
                                ProcessInput();
                            }
                            break;
                        case Action.OutCompleted:
                            int bytesSent = EndWrite(socketError, bytesTransferred);

                            //  IO error has occurred. We stop waiting for output events.
                            //  The engine is not terminated until we detect input error;
                            //  this is necessary to prevent losing incoming messages.
                            if (bytesSent == -1)
                            {
                                m_sendingState = SendState.Error;
                            }
                            else
                            {
                                m_outpos.AdvanceOffset(bytesSent);
                                m_outsize -= bytesSent;

                                BeginSending();
                            }
                            break;
                        case Action.ActivateOut:
                            // if we idle we start sending, other than do nothing
                            if (m_sendingState == SendState.Idle)
                            {
                                m_sendingState = SendState.Active;
                                BeginSending();
                            }
                            break;
                        default:
                            Debug.Assert(false);
                            break;
                    }
                    break;
                case State.Stalled:
                    switch (action)
                    {
                        case Action.ActivateIn:
                            //  There was an input error but the engine could not
                            //  be terminated (due to the stalled decoder).
                            //  Flush the pending message and terminate the engine now.
                            m_decoder.ProcessBuffer(m_inpos, 0);
                            Debug.Assert(!m_decoder.Stalled());
                            m_session.Flush();
                            Error();
                            break;
                        case Action.ActivateOut:
                            break;
                    }
                    break;
            }
        }
Exemple #15
0
        public StreamEngine(AsyncSocket handle, Options options, string endpoint)
        {
            m_handle = handle;
            m_insize = 0;
            m_ioEnabled = false;
            m_sendingState = SendState.Idle;
            m_receivingState = ReceiveState.Idle;
            m_outsize = 0;
            m_session = null;
            m_options = options;
            m_plugged = false;
            m_endpoint = endpoint;
            m_socket = null;
            m_encoder = null;
            m_decoder = null;
            m_actionsQueue = new Queue<StateMachineAction>();

            //  Set the socket buffer limits for the underlying socket.
            if (m_options.SendBuffer != 0)
            {
                m_handle.SendBufferSize = m_options.SendBuffer;
            }
            if (m_options.ReceiveBuffer != 0)
            {
                m_handle.ReceiveBufferSize = m_options.ReceiveBuffer;
            }
        }
Exemple #16
0
        private void Activate()
        {
            //  Handshaking was successful.
            //  Switch into the normal message flow.
            m_state = State.Active;

            m_outsize = 0;

            m_sendingState = SendState.Active;
            BeginSending();

            m_receivingState = ReceiveState.Active;

            if (m_insize == 0)
            {
                m_decoder.GetBuffer(out m_inpos, out m_insize);
                BeginRead(m_inpos, m_insize);
            }
            else
            {
                ProcessInput();
            }
        }
Exemple #17
0
        private void BeginSending()
        {
            if (m_outsize == 0)
            {
                m_outpos = null;
                m_encoder.GetData(ref m_outpos, ref m_outsize);

                if (m_outsize == 0)
                {
                    m_sendingState = SendState.Idle;
                }
                else
                {
                    BeginWrite(m_outpos, m_outsize);
                }
            }
            else
            {
                BeginWrite(m_outpos, m_outsize);
            }
        }
Exemple #18
0
        public void Send(UdpPacket packet)
        {
            if (this._state != ClientState.Working)
            {
                return;
            }

            //异步发送
            IPEndPoint remoteIpEp = new IPEndPoint(packet.Address, packet.Port);

            packet.GenerateID();

            LoggerFactory.Debug("parepare send packet:{0}", packet);

            EncodeResult result = null;

            try
            {
                IPacketEncoder encoder = PacketEncoderFactory.CreateEncoder(packet);
                LoggerFactory.Debug("get encoder:{0}", encoder.GetType().Name);

                result = encoder.Encode();
                LoggerFactory.Debug("encode packet:{0}", result);

                if (result.Length > UDP_MAX_BUF_SIZE)
                {
                    //超过大小的分包处理
                    MultiUdpPacket mpacket = new MultiUdpPacket(result.Fragments[0]);
                    mpacket.ID                = packet.ID;
                    mpacket.ParentID          = packet.ID;
                    mpacket.MaxFragmentLength = UDP_MAX_BUF_SIZE - MultiUdpPacket.HEAD_SIZE;

                    encoder = PacketEncoderFactory.CreateEncoder(mpacket);
                    LoggerFactory.Debug("get encoder:{0}", encoder.GetType().Name);

                    result = encoder.Encode();
                    LoggerFactory.Debug("encode packet:{0}", result);
                }
            }
            catch (Exception e)
            {
                OnSendPackage(packet, false);
                OnError(Errors.EncodeError, "加密包错误。", e);
            }

            try
            {
                for (int i = 0; i < result.Fragments.Count; i++)
                {
                    byte[]    buf   = result.Fragments[i];
                    SendState state = new SendState();
                    state.LastPacket = i == result.Fragments.Count - 1;
                    state.Packet     = packet;
                    _client.BeginSend(buf, buf.Length, remoteIpEp, new AsyncCallback(AsyncSendHandler), state);
                    Thread.Sleep(20);//稍微等待一下,避免丢包
                }
            }
            catch (Exception e)
            {
                OnSendPackage(packet, false);
                OnError(Errors.NetworkError, "发送包错误。", e);
            }
        }
Exemple #19
0
 protected override void BeginSend(byte[] data, int size, AsyncCallback on_completed, SendState state) => client.Client.BeginSend(data, 0, size, SocketFlags.None, on_completed, state);
Exemple #20
0
        public virtual bool Send()
        {
            if (string.IsNullOrEmpty(From))
            {
                sendState = SendState.Error;
                message   = "没有发件人!";
                return(false);
            }
            if (string.IsNullOrEmpty(Subject))
            {
                sendState = SendState.Error;
                message   = "没有邮件标题!";
                return(false);
            }
            if (string.IsNullOrEmpty(Body))
            {
                sendState = SendState.Error;
                message   = "没有邮件正文!";
                return(false);
            }
            if (To.Count < 1)
            {
                sendState = SendState.Error;
                message   = "没有收件人!";
                return(false);
            }
            if (string.IsNullOrEmpty(Server))
            {
                sendState = SendState.Error;
                message   = "没有设置邮件服务器地址!";
                return(false);
            }
            if (string.IsNullOrEmpty(Password))
            {
                sendState = SendState.Error;
                message   = "没有设置邮件服务器账号密码!";
                return(false);
            }
            if (string.IsNullOrEmpty(UserName))
            {
                UserName = From;
            }
            MailMessage mailMessage = new MailMessage();

            mailMessage.From            = new MailAddress(From, FromName);
            mailMessage.Subject         = Subject.Trim();
            mailMessage.SubjectEncoding = SubjectEncoding;
            mailMessage.Body            = Body.Trim();
            mailMessage.BodyEncoding    = BodyEncoding;
            mailMessage.IsBodyHtml      = IsBodyHtml;
            foreach (string mailAttachment in mailAttachmentList)
            {
                mailMessage.Attachments.Add(new Attachment(mailAttachment));
            }
            StringEnumerator enumerator2 = To.GetEnumerator();

            try
            {
                while (enumerator2.MoveNext())
                {
                    string      current2    = enumerator2.Current;
                    string[]    array       = current2.Split(Delimiter);
                    MailAddress mailAddress = null;
                    mailAddress = ((array.Length <= 1) ? new MailAddress(array[0].Trim()) : new MailAddress(array[0].Trim(), array[1].Trim()));
                    mailMessage.To.Add(mailAddress);
                }
            }
            finally
            {
                (enumerator2 as IDisposable)?.Dispose();
            }
            if (Bcc.Count > 0)
            {
                enumerator2 = Bcc.GetEnumerator();
                try
                {
                    while (enumerator2.MoveNext())
                    {
                        string      current3    = enumerator2.Current;
                        string[]    array2      = current3.Split(Delimiter);
                        MailAddress mailAddress = null;
                        mailAddress = ((array2.Length <= 1) ? new MailAddress(array2[0].Trim()) : new MailAddress(array2[0].Trim(), array2[1].Trim()));
                        mailMessage.Bcc.Add(mailAddress);
                    }
                }
                finally
                {
                    (enumerator2 as IDisposable)?.Dispose();
                }
            }
            if (CC.Count > 0)
            {
                enumerator2 = CC.GetEnumerator();
                try
                {
                    while (enumerator2.MoveNext())
                    {
                        string      current3    = enumerator2.Current;
                        string[]    array3      = current3.Split(Delimiter);
                        MailAddress mailAddress = null;
                        mailAddress = ((array3.Length <= 1) ? new MailAddress(array3[0].Trim()) : new MailAddress(array3[0].Trim(), array3[1].Trim()));
                        mailMessage.CC.Add(mailAddress);
                    }
                }
                finally
                {
                    (enumerator2 as IDisposable)?.Dispose();
                }
            }
            try
            {
                SmtpClient smtpClient = new SmtpClient(Server, ServerPort);
                smtpClient.Credentials    = new NetworkCredential(UserName, Password);
                smtpClient.SendCompleted += SendCompletedCallback;
                string subject = Subject;
                smtpClient.Send(mailMessage);
            }
            catch (Exception ex)
            {
                sendState = SendState.Error;
                message   = ex.Message;
                return(false);
            }
            mailMessage.Dispose();
            return(true);
        }
Exemple #21
0
        void OnReceiveTrData(object sender, _DKHOpenAPIEvents_OnReceiveTrDataEvent e)
        {
            int index = Array.FindIndex(catalogTR, o => o.ToString().Contains(e.sTrCode.Substring(1)));

            if (index < 1)
            {
                new ExceptionMessage(e.sTrCode);

                return;
            }
            if (index < 5 && index > 0)
            {
                var temp = API.GetCommDataEx(e.sTrCode, e.sRQName);

                if (temp != null)
                {
                    string[,] ts = new string[((object[, ])temp).GetUpperBound(0) + 1, ((object[, ])temp).GetUpperBound(1) + 1];
                    int x, y, lx = ((object[, ])temp).GetUpperBound(0), ly = ((object[, ])temp).GetUpperBound(1);

                    for (x = 0; x <= lx; x++)
                    {
                        var sb = new StringBuilder(64);

                        for (y = 0; y <= ly; y++)
                        {
                            ts[x, y] = (string)((object[, ])temp)[x, y];

                            if (ts[x, y].Length > 13 && e.sRQName.Split(';')[1].Equals(ts[x, y].Substring(2)))
                            {
                                sb          = Exists;
                                e.sPrevNext = "0";

                                break;
                            }
                            sb.Append(ts[x, y]).Append(';');
                        }
                        if (Exists.Equals(sb) == false)
                        {
                            SendMemorize?.Invoke(this, new Memorize(sb));

                            continue;
                        }
                        if (Exists.Equals(sb))
                        {
                            break;
                        }
                    }
                    if (DeadLine && (e.sRQName.Split(';')[1].Length == 8 || e.sRQName.Split(';')[1].Equals("DoesNotExist")) && e.sPrevNext.Equals("2"))
                    {
                        request.RequestTrData(new Task(() => InputValueRqData(new Opt10081
                        {
                            Value    = e.sRQName.Split(';')[0],
                            RQName   = e.sRQName,
                            PrevNext = 2
                        })));
                        return;
                    }
                    if (DeadLine == false && e.sRQName.Split(';')[0].Length == 6 && e.sPrevNext.Equals("2"))
                    {
                        request.RequestTrData(new Task(() => InputValueRqData(new Opt10079
                        {
                            Value    = e.sRQName.Split(';')[0],
                            RQName   = e.sRQName,
                            PrevNext = 2
                        })));
                        return;
                    }
                    if (DeadLine == false && e.sRQName.Substring(5, 3).Equals("000") && e.sPrevNext.Equals("2"))
                    {
                        request.RequestTrData(new Task(() => InputValueRqData(new Opt50028
                        {
                            Value    = e.sRQName.Substring(0, 8),
                            RQName   = e.sRQName,
                            PrevNext = 2
                        })));
                        return;
                    }
                    if (DeadLine == false && e.sRQName.Split(';')[0].Length == 8 && e.sPrevNext.Equals("2"))
                    {
                        request.RequestTrData(new Task(() => InputValueRqData(new Opt50066
                        {
                            Value    = e.sRQName.Substring(0, 8),
                            RQName   = e.sRQName,
                            PrevNext = 2
                        })));
                        return;
                    }
                    if (e.sPrevNext.Equals("0"))
                    {
                        SendMemorize?.Invoke(this, new Memorize(e.sPrevNext, e.sRQName.Split(';')[0]));
                    }
                }
                SetScreenNumber(9000, 9031);
                SendMemorize?.Invoke(this, new Memorize("Clear"));
                Request(GetRandomCode(new Random().Next(0, CodeList.Count)));

                return;
            }
            var str = new StringBuilder(512);
            int i, cnt = API.GetRepeatCnt(e.sTrCode, e.sRQName);

            for (i = 0; i < (cnt > 0 ? cnt : cnt + 1); i++)
            {
                foreach (string item in Array.Find(catalogTR, o => o.ToString().Contains(e.sTrCode.Substring(1))))
                {
                    str.Append(API.GetCommData(e.sTrCode, e.sRQName, i, item).Trim()).Append(';');
                }

                if (cnt > 0)
                {
                    str.Append("*");
                }
            }
            switch (Array.FindIndex(catalogTR, o => o.ToString().Contains(e.sTrCode.Substring(1))))
            {
            case 5:
                FixUp(str.ToString().Split(';'), e.sRQName);
                return;

            case 6:
                foreach (string info in str.ToString().Split('*'))
                {
                    FixUp(info.Split(';'));
                }

                return;

            case 7:
            case 8:
                if (str.Length > 1 && e.sRQName.Equals("DoNotRollOver") == false)
                {
                    if (e.sScrNo.Substring(0, 1).Equals("1"))
                    {
                        SellOrder[str.ToString().Split(';')[0]] = double.Parse(e.sRQName.Split(';')[0]);
                    }

                    else if (e.sScrNo.Substring(0, 1).Equals("2"))
                    {
                        BuyOrder[str.ToString().Split(';')[0]] = double.Parse(e.sRQName.Split(';')[0]);
                    }
                }
                SendState?.Invoke(this, new State(OnReceiveBalance, SellOrder.Count, Quantity, BuyOrder.Count, ScreenNumber));
                return;

            case 9:
                SendState?.Invoke(this, new State(OnReceiveBalance, SellOrder.Count, Quantity, BuyOrder.Count, ScreenNumber));
                return;

            case 10:
                SendDeposit?.Invoke(this, new Deposit(str.ToString().Split(';')));
                break;

            case 11:
                new Task(() =>
                {
                    var temporary = str.ToString().Split('*');

                    for (i = 0; i < temporary.Length; i++)
                    {
                        if (temporary[i].Length > 0 && temporary[i].Substring(0, 8).Equals(API.GetFutureCodeByIndex(0)))
                        {
                            var quantity = temporary[i].Split(';');
                            Quantity     = quantity[2].Equals("1") ? -int.Parse(quantity[3]) : int.Parse(quantity[3]);
                            AvgPurchase  = (double.Parse(quantity[4]) / 100).ToString("F2");
                        }
                    }
                    SendBalance?.Invoke(this, new Balance(temporary));
                }).Start();
                break;
            }
        }
Exemple #22
0
 void tmr_Tick(object sender, EventArgs e)
 {
     tmr.Stop();
     Console.WriteLine("Time Out!!!");
     _InData.Clear();
     _crtSendState = SendState.IDEL;
 }
Exemple #23
0
        public void SendPackets(IEnumerable<Packet> pkts)
        {
            try
            {
                foreach (var i in pkts)
                    pendingPackets.Enqueue(i);
                if (CanSendPacket(send, false))
                {
                    var dat = (send.UserToken as SendToken).Packet.Write(parent);

                    sendState = SendState.Sending;
                    send.SetBuffer(dat, 0, dat.Length);
                    if (!skt.SendAsync(send))
                        IOCompleted(this, send);
                }
            }
            catch
            {
                logger.Error("Error sending packets, check Client.cs");
            }
        }
Exemple #24
0
        private void DealwithDataIn()
        {

            string outstr = "Data Received:";
            foreach (var item in _InData)
            {
                outstr += "0x" + item.ToString("X2") + " ";
            }
            Console.WriteLine(outstr);
            if (_crtSendState != SendState.RECEIVEING)
            {

                Console.WriteLine("RECEIVEING ERROR");
                _InData.Clear();
                _crtSendState = SendState.IDEL;
                if (IsTransfer)
                {
                    eventWait.Set();
                }
                return;
            }
            if (_InData.Count >= 5)
            {
                if (_InData[0] != 0xFE || _InData[1] != 0xFC)
                {
                    Console.WriteLine("STX ERROR");
                    _InData.Clear();
                    _crtSendState = SendState.IDEL;
                    if (IsTransfer)
                    {
                        eventWait.Set();
                    }
                    return;
                }
                if (_InData[2] < _InData.Count - 3)
                {
                    _InData.Clear();
                    _crtSendState = SendState.IDEL;
                    if (IsTransfer)
                    {
                        eventWait.Set();
                    }
                    return;
                }
                if (_InData[2] == _InData.Count - 3)
                {
                    tmr.Stop();
                    Console.WriteLine("Receive Ok!!!!!!!!!");
                    byte[] tmp = _InData.ToArray();
                    _InData.Clear();
                    _crtSendState = SendState.IDEL;
                    DecodeMsg(tmp);
                }

            }
        }
        void SendCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                bool repeat;
                do
                {
                    repeat = false;

                    if (e.SocketError != SocketError.Success)
                        throw new SocketException((int)e.SocketError);

                    switch (sendState)
                    {
                        case SendState.Ready:
                            var len = (e.UserToken as SendToken).Packet.Write(parent, sendBuff, 0);

                            sendState = SendState.Sending;
                            e.SetBuffer(sendBuff, 0, len);
                            if (!skt.SendAsync(e))
                            {
                                repeat = true;
                                continue;
                            }
                            break;
                        case SendState.Sending:
                            (e.UserToken as SendToken).Packet = null;

                            if (CanSendPacket(e, true))
                            {
                                repeat = true;
                                continue;
                            }
                            break;
                        default:
                            throw new InvalidOperationException(e.LastOperation.ToString());
                    }
                } while (repeat);
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
 private bool CanSendPacket(SocketAsyncEventArgs e, bool ignoreSending)
 {
     lock (sendLock)
     {
         if (sendState == SendState.Ready ||
             (!ignoreSending && sendState == SendState.Sending))
             return false;
         Packet packet;
         if (pendingPackets.TryDequeue(out packet))
         {
             (e.UserToken as SendToken).Packet = packet;
             sendState = SendState.Ready;
             return true;
         }
         sendState = SendState.Awaiting;
         return false;
     }
 }
        public void SendPackets(IEnumerable<Packet> pkts)
        {
            if (!skt.Connected) return;
            foreach (Packet i in pkts)
                pendingPackets.Enqueue(i);
            if (CanSendPacket(send, false))
            {
                int len = (send.UserToken as SendToken).Packet.Write(parent, sendBuff, 0);

                sendState = SendState.Sending;
                send.SetBuffer(sendBuff, 0, len);
                if (!skt.SendAsync(send))
                    SendCompleted(this, send);
            }
        }
        public void SendPackets(IEnumerable<Packet> pkts)
        {
            try
            {
                foreach (var i in pkts)
                    pendingPackets.Enqueue(i);
                if (CanSendPacket(send, false))
                {
                    var dat = (send.UserToken as SendToken).Packet.Write(parent);

                    sendState = SendState.Sending;
                    send.SetBuffer(dat, 0, dat.Length);
                    if (!skt.SendAsync(send))
                        IOCompleted(this, send);
                }
            }
            catch
            {
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine(@"Error sending packets, check ClientProcessor.cs");
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
        /// <summary>
        /// Sends a payload on the socket.
        /// </summary>
        private void SendPayloadAsync(SendState sendState)
        {
            TcpClientPayload payload;

            try
            {
                // Quit if this send loop has been cancelled
                if (sendState.Token.Cancelled)
                    return;

                if (sendState.SendQueue.TryDequeue(out payload))
                {
                    // Save the payload currently
                    // being sent to the send state
                    sendState.Payload = payload;

                    // Ensure that the payload fits in the send buffer
                    if (payload.Length > sendState.SendArgs.Buffer.Length)
                        sendState.SendArgs.SetBuffer(new byte[payload.Length], 0, payload.Length);
                    else
                        sendState.SendArgs.SetBuffer(0, payload.Length);

                    // Copy payload into send buffer
                    Buffer.BlockCopy(payload.Data, payload.Offset, sendState.SendArgs.Buffer, 0, payload.Length);

                    // Send payload to the client asynchronously
                    if (!sendState.Socket.SendAsync(sendState.SendArgs))
                        ThreadPool.QueueUserWorkItem(state => ProcessSend((SendState)state), sendState);
                }
                else
                {
                    // No more payloads to send, so stop sending payloads
                    Interlocked.Exchange(ref sendState.Sending, 0);

                    // Double-check to ensure that a new payload didn't appear before exiting the send loop
                    if (!sendState.SendQueue.IsEmpty && Interlocked.CompareExchange(ref sendState.Sending, 1, 0) == 0)
                        ThreadPool.QueueUserWorkItem(state => SendPayloadAsync((SendState)state), sendState);
                }
            }
            catch (Exception ex)
            {
                // Log exception during send operation
                OnSendDataException(ex);

                // Continue asynchronous send loop
                ThreadPool.QueueUserWorkItem(state => SendPayloadAsync((SendState)state), sendState);
            }
            finally
            {
                // If the operation was cancelled during execution,
                // make sure to dispose of allocated resources
                if (sendState.Token.Cancelled)
                    sendState.Dispose();
            }
        }
Exemple #30
0
        void OnReceiveChejanData(object sender, _DKHOpenAPIEvents_OnReceiveChejanDataEvent e)
        {
            var sb    = new StringBuilder(256);
            var index = int.Parse(e.sGubun);

            foreach (int fid in catalogReal[index])
            {
                sb.Append(API.GetChejanData(fid)).Append(';');
            }

            var param = sb.ToString().Split(';');

            switch (index)
            {
            case 0:
                if (param[3].Equals(Code))
                {
                    switch (param[5])
                    {
                    case "체결":
                        if (param[14].Equals("1") ? SellOrder.Remove(param[1]) : BuyOrder.Remove(param[1]))
                        {
                            OnReceiveBalance = false;
                        }

                        break;

                    case "접수":
                        if (int.Parse(param[11]) == 0)
                        {
                            OnReceiveBalance = request.QueueCount == 0 ? true : false;
                        }

                        break;

                    case "확인":
                        if (param[12].Substring(3).Equals("취소") || param[12].Substring(3).Equals("정정"))
                        {
                            OnReceiveBalance = request.QueueCount == 0 ? true : false;
                        }

                        break;
                    }
                    SendState?.Invoke(this, new State(OnReceiveBalance, SellOrder.Count, Quantity, BuyOrder.Count, ScreenNumber));
                }
                return;

            case 1:
                return;

            case 4:
                if (param[1].Equals(Code))
                {
                    Quantity         = param[9].Equals("1") ? -int.Parse(param[4]) : int.Parse(param[4]);
                    AvgPurchase      = param[5];
                    OnReceiveBalance = request.QueueCount == 0 ? true : false;
                    SendState?.Invoke(this, new State(OnReceiveBalance, SellOrder.Count, Quantity, BuyOrder.Count, ScreenNumber));
                }
                return;
            }
        }
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="TcpClient"/> and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                try
                {
                    if (disposing)
                    {
                        if ((object)m_connectState != null)
                        {
                            TerminateConnection(m_connectState.Token);
                            m_connectState.Dispose();
                            m_connectState = null;
                        }

                        if ((object)m_receiveState != null)
                        {
                            m_receiveState.Dispose();
                            m_receiveState = null;
                        }

                        if ((object)m_sendState != null)
                        {
                            m_sendState.Dispose();
                            m_sendState = null;
                        }

                        if ((object)m_connectWaitHandle != null)
                        {
                            m_connectWaitHandle.Set();
                            m_connectWaitHandle.Dispose();
                            m_connectWaitHandle = null;
                        }
                    }
                }
                finally
                {
                    m_disposed = true;          // Prevent duplicate dispose.
                    base.Dispose(disposing);    // Call base class Dispose().
                }
            }
        }
Exemple #32
0
        private void SendOneFile(string fileName, string flashName = "")
        {
            if (string.IsNullOrWhiteSpace(flashName))
                flashName = Path.GetFileName(fileName);

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                _headerTop.Add(string.Format("const char FNAME{0:D3}[] PROGMEM = \"{1}\";" + Environment.NewLine, 
                    _flashFileNo, flashName));
                _headerBottom.Add(string.Format("  {{ FNAME{0:D3}, {1,3:D}, {2:D} }}," + Environment.NewLine, 
                    _flashFileNo, _flashOffset / DATAFLASH_PAGE_BYTES, fs.Length));

                serialPort1.Write("START " + _flashOffset.ToString() + " " + fs.Length.ToString() + "\n");
                _sendState = SendState.WAITFORSEND;

                byte[] myBuff = new byte[DATAFLASH_PAGE_BYTES];
                int r;
                while ((r = fs.Read(myBuff, 0, myBuff.Length)) > 0)
                {
                    serialPort1.Write(myBuff, 0, r);
                    _flashOffset += r;
                }
                fs.Close();
            }

            // Round up to the next page
            _flashOffset = ((_flashOffset / DATAFLASH_PAGE_BYTES) + 1) * DATAFLASH_PAGE_BYTES;
            ++_flashFileNo;
            _sendState = SendState.SENDINGFILE;
        }
        private void ProcessIntegratedSecurityAuthentication(IAsyncResult asyncResult)
        {
            ConnectState connectState = null;
            ReceiveState receiveState = null;
            SendState sendState = null;

            try
            {
                // Get the connect state from the async result
                connectState = (ConnectState)asyncResult.AsyncState;

                // Quit if this connection loop has been cancelled
                if (connectState.Token.Cancelled)
                    return;

                try
                {
                    // Complete the operation to authenticate with the server
                    connectState.NegotiateStream.EndAuthenticateAsClient(asyncResult);
                }
                catch (InvalidCredentialException)
                {
                    if (!m_ignoreInvalidCredentials)
                        throw;
                }

                // Initialize the SocketAsyncEventArgs for receive operations
                connectState.ReceiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                connectState.ReceiveArgs.SetBuffer(new byte[ReceiveBufferSize], 0, ReceiveBufferSize);

                if (m_payloadAware)
                    connectState.ReceiveArgs.Completed += (sender, args) => ProcessReceivePayloadAware((ReceiveState)args.UserToken);
                else
                    connectState.ReceiveArgs.Completed += (sender, args) => ProcessReceivePayloadUnaware((ReceiveState)args.UserToken);

                // Initialize the SocketAsyncEventArgs for send operations
                connectState.SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction();
                connectState.SendArgs.SetBuffer(new byte[SendBufferSize], 0, SendBufferSize);
                connectState.SendArgs.Completed += (sender, args) => ProcessSend((SendState)args.UserToken);

                // Initialize state object for the asynchronous send loop
                sendState = new SendState();
                sendState.Token = connectState.Token;
                sendState.Socket = connectState.Socket;
                sendState.ReceiveArgs = connectState.ReceiveArgs;
                sendState.SendArgs = connectState.SendArgs;
                sendState.SendArgs.UserToken = sendState;

                // Store sendState in m_sendState so that calls to Disconnect
                // and Dispose can dispose resources and cancel asynchronous loops
                m_sendState = sendState;

                // Check the state of cancellation one more time before
                // proceeding to the next step of the connection loop
                if (connectState.Token.Cancelled)
                    return;

                // Notify of established connection
                // and begin receiving data.
                m_connectWaitHandle.Set();
                OnConnectionEstablished();

                // Initialize state object for the asynchronous receive loop
                receiveState = new ReceiveState();
                receiveState.Token = connectState.Token;
                receiveState.Socket = connectState.Socket;
                receiveState.Buffer = connectState.ReceiveArgs.Buffer;
                receiveState.ReceiveArgs = connectState.ReceiveArgs;
                receiveState.ReceiveArgs.UserToken = receiveState;
                receiveState.SendArgs = connectState.SendArgs;

                // Store receiveState in m_receiveState so that calls to Disconnect
                // and Dispose can dispose resources and cancel asynchronous loops
                m_receiveState = receiveState;

                // Start receiving data
                if (m_payloadAware)
                    ReceivePayloadAwareAsync(receiveState);
                else
                    ReceivePayloadUnawareAsync(receiveState);

                // Further socket interactions are handled through the SslStream
                // object, so the SocketAsyncEventArgs is no longer needed
                connectState.ConnectArgs.Dispose();
            }
            catch (SocketException ex)
            {
                // Log exception during connection attempt
                OnConnectionException(ex);

                // If connectState is null, we cannot proceed
                if ((object)connectState == null)
                    return;

                // If the connection is refused by the server,
                // keep trying until we reach our maximum connection attempts
                if (ex.SocketErrorCode == SocketError.ConnectionRefused &&
                    (MaxConnectionAttempts == -1 || connectState.ConnectionAttempts < MaxConnectionAttempts))
                {
                    try
                    {
                        ConnectAsync(connectState);
                    }
                    catch
                    {
                        TerminateConnection(connectState.Token);
                    }
                }
                else
                {
                    // For any other socket exception,
                    // terminate the connection
                    TerminateConnection(connectState.Token);
                }
            }
            catch (Exception ex)
            {
                // Log exception during connection attempt
                string errorMessage = $"Unable to authenticate connection to server: {ex.Message}";
                OnConnectionException(new Exception(errorMessage, ex));

                // Terminate the connection
                if ((object)connectState != null)
                    TerminateConnection(connectState.Token);
            }
            finally
            {
                if ((object)connectState != null)
                {
                    // If the operation was cancelled during execution,
                    // make sure to dispose of erroneously allocated resources;
                    // otherwise, dispose of the NegotiateStream which is only used for authentication
                    if (connectState.Token.Cancelled)
                    {
                        connectState.Dispose();
                    }
                    else
                    {
                        connectState.NetworkStream.Dispose();
                        connectState.NegotiateStream.Dispose();
                    }
                }

                if ((object)receiveState != null && receiveState.Token.Cancelled)
                    receiveState.Dispose();

                if ((object)sendState != null && sendState.Token.Cancelled)
                    sendState.Dispose();
            }
        }
Exemple #34
0
        private void Handle(Action action, SocketError socketError, int bytesTransferred)
        {
            switch (m_state)
            {
            case State.Closed:
                switch (action)
                {
                case Action.Start:
                    if (m_options.RawSocket)
                    {
                        m_encoder = new RawEncoder(Config.OutBatchSize, m_session, m_options.Endian);
                        m_decoder = new RawDecoder(Config.InBatchSize, m_options.MaxMessageSize, m_session, m_options.Endian);

                        Activate();
                    }
                    else
                    {
                        m_state          = State.Handshaking;
                        m_handshakeState = HandshakeState.Closed;
                        HandleHandshake(action, socketError, bytesTransferred);
                    }

                    break;
                }
                break;

            case State.Handshaking:
                HandleHandshake(action, socketError, bytesTransferred);
                break;

            case State.Active:
                switch (action)
                {
                case Action.InCompleted:
                    m_insize = EndRead(socketError, bytesTransferred);

                    ProcessInput();
                    break;

                case Action.ActivateIn:

                    // if we stuck let's continue, other than that nothing to do
                    if (m_receivingState == ReceiveState.Stuck)
                    {
                        m_receivingState = ReceiveState.Active;
                        ProcessInput();
                    }
                    break;

                case Action.OutCompleted:
                    int bytesSent = EndWrite(socketError, bytesTransferred);

                    // IO error has occurred. We stop waiting for output events.
                    // The engine is not terminated until we detect input error;
                    // this is necessary to prevent losing incoming messages.
                    if (bytesSent == -1)
                    {
                        m_sendingState = SendState.Error;
                    }
                    else
                    {
                        m_outpos.AdvanceOffset(bytesSent);
                        m_outsize -= bytesSent;

                        BeginSending();
                    }
                    break;

                case Action.ActivateOut:
                    // if we idle we start sending, other than do nothing
                    if (m_sendingState == SendState.Idle)
                    {
                        m_sendingState = SendState.Active;
                        BeginSending();
                    }
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }
                break;

            case State.Stalled:
                switch (action)
                {
                case Action.ActivateIn:
                    // There was an input error but the engine could not
                    // be terminated (due to the stalled decoder).
                    // Flush the pending message and terminate the engine now.
                    m_decoder.ProcessBuffer(m_inpos, 0);
                    Debug.Assert(!m_decoder.Stalled());
                    m_session.Flush();
                    Error();
                    break;

                case Action.ActivateOut:
                    break;
                }
                break;
            }
        }
/*
        public void SendPacket(Packet pkt)
        {
            try
            {
                pendingPackets.Enqueue(pkt);
                if (CanSendPacket(send, false))
                {
                    var dat = (send.UserToken as SendToken).Packet.Write(parent);

                    sendState = SendState.Sending;
                    send.SetBuffer(dat, 0, dat.Length);
                    if (!skt.SendAsync(send))
                        IOCompleted(this, send);
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine(e);
                //Console.WriteLine("Error sending packet with ID " + pkt.ID);
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
        */
//        object sendLock = new object();
        public void SendPacket(Packet pkt)
        {
            try
            {
                pendingPackets.Enqueue(pkt);
                if (CanSendPacket(send, false))
                {
                    var dat = (send.UserToken as SendToken).Packet.Write(parent);

                    sendState = SendState.Sending;
                    send.SetBuffer(dat, 0, dat.Length);
                    if (!skt.SendAsync(send))
                        IOCompleted(this, send);
                }
            }
            catch
            {
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine("Error sending packet with ID " + pkt.ID.ToString());
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
        void IOCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                bool repeat;
                do
                {
                    repeat = false;

                    if (e.SocketError != SocketError.Success)
                        throw new SocketException((int)e.SocketError);

                    if (e.LastOperation == SocketAsyncOperation.Receive)
                    {
                        switch (receiveState)
                        {
                            case ReceiveState.ReceivingHdr:
                                if (e.BytesTransferred < 5)
                                {
                                    parent.Disconnect();
                                    return;
                                }

                                var len = (e.UserToken as ReceiveToken).Length =
                                    IPAddress.NetworkToHostOrder(BitConverter.ToInt32(e.Buffer, 0)) - 5;
                                if (len < 0 || len > BUFFER_SIZE)
                                    throw new InternalBufferOverflowException();
                                (e.UserToken as ReceiveToken).Packet = Packet.Packets[(PacketID)e.Buffer[4]].CreateInstance();

                                receiveState = ReceiveState.ReceivingBody;
                                e.SetBuffer(0, len);
                                if (!skt.ReceiveAsync(e))
                                {
                                    repeat = true;
                                    continue;
                                }
                                break;
                            case ReceiveState.ReceivingBody:
                                if (e.BytesTransferred < (e.UserToken as ReceiveToken).Length)
                                {
                                    parent.Disconnect();
                                    return;
                                }

                                var pkt = (e.UserToken as ReceiveToken).Packet;
                                pkt.Read(parent, e.Buffer, (e.UserToken as ReceiveToken).Length);

                                receiveState = ReceiveState.Processing;
                                bool cont = OnPacketReceived(pkt);

                                if (cont)
                                {
                                    receiveState = ReceiveState.ReceivingHdr;
                                    e.SetBuffer(0, 5);
                                    if (!skt.ReceiveAsync(e))
                                    {
                                        repeat = true;
                                        continue;
                                    }
                                }
                                break;
                            default:
                                throw new InvalidOperationException(e.LastOperation.ToString());
                        }
                    }
                    else if (e.LastOperation == SocketAsyncOperation.Send)
                    {
                        switch (sendState)
                        {
                            case SendState.Ready:
                                var dat = (e.UserToken as SendToken).Packet.Write(parent);

                                sendState = SendState.Sending;
                                e.SetBuffer(dat, 0, dat.Length);
                                if (!skt.SendAsync(e))
                                {
                                    repeat = true;
                                    continue;
                                }
                                break;
                            case SendState.Sending:
                                (e.UserToken as SendToken).Packet = null;

                                if (CanSendPacket(e,true))
                                {
                                    repeat = true;
                                    continue;
                                }
                                break;
                            default:
                                throw new InvalidOperationException(e.LastOperation.ToString());
                        }
                    }
                    else
                        throw new InvalidOperationException(e.LastOperation.ToString());
                } while (repeat);
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
        private void IOCompleted(object sender, SocketAsyncEventArgs e)
        {

            try
            {
                bool repeat;
                do
                {
                    repeat = false;

                    if (e.SocketError != SocketError.Success)
                        throw new SocketException((int) e.SocketError);
                    /*
                    SocketError errorCode;
                    int nBytesRec = Socket.EndReceive(ar, out errorCode);
                    if (errorCode != SocketError.Success)
                    {
                        nBytesRec = 0;
                    }
                    */
                    if (e.LastOperation == SocketAsyncOperation.Receive)
                    {
                        switch (receiveState)
                        {
                            case ReceiveState.ReceivingHdr:
                                if (debug)
                                    Console.WriteLine(@"test");

                                if (e.BytesTransferred < 5)
                                {
                                    parent.Disconnect();
                                    return;
                                }

                                if (debug)
                                    Console.WriteLine(@"test2");

                                if (e.Buffer[0] == 0x3c && e.Buffer[1] == 0x70 &&
                                    e.Buffer[2] == 0x6f && e.Buffer[3] == 0x6c && e.Buffer[4] == 0x69)
                                {
                                    ProcessPolicyFile();
                                    return;
                                }

                                var len = (e.UserToken as ReceiveToken).Length =
                                    IPAddress.NetworkToHostOrder(BitConverter.ToInt32(e.Buffer, 0)) - 5;
                                if (len < 0 || len > BUFFER_SIZE)
                                    throw new InternalBufferOverflowException();
                                (e.UserToken as ReceiveToken).Packet =
                                    Packet.Packets[(PacketID) e.Buffer[4]].CreateInstance();
                                if (debug)
                                    Console.WriteLine("test3 - " + (e.UserToken as ReceiveToken).Packet.GetType().Name);

                                receiveState = ReceiveState.ReceivingBody;
                                e.SetBuffer(0, len);
                                if (!skt.ReceiveAsync(e))
                                {
                                    repeat = true;
                                }
                                break;
                            case ReceiveState.ReceivingBody:
                                if (e.BytesTransferred < (e.UserToken as ReceiveToken).Length)
                                {
                                    parent.Disconnect();
                                    return;
                                }

                                var pkt = (e.UserToken as ReceiveToken).Packet;
                                pkt.Read(parent, e.Buffer, (e.UserToken as ReceiveToken).Length);

                                receiveState = ReceiveState.Processing;
                                var cont = OnPacketReceived(pkt);

                                if (cont && skt.Connected)
                                {
                                    receiveState = ReceiveState.ReceivingHdr;
                                    e.SetBuffer(0, 5);
                                    if (!skt.ReceiveAsync(e))
                                    {
                                        repeat = true;
                                    }
                                }
                                break;
                            default:
                                throw new InvalidOperationException(e.LastOperation.ToString());
                        }
                    }
                    else if (e.LastOperation == SocketAsyncOperation.Send)
                    {
                        switch (sendState)
                        {
                            case SendState.Ready:
                                var dat = (e.UserToken as SendToken).Packet.Write(parent);

                                sendState = SendState.Sending;
                                e.SetBuffer(dat, 0, dat.Length);
                                if (!skt.SendAsync(e))
                                {
                                    repeat = true;
                                }
                                break;
                            case SendState.Sending:
                                (e.UserToken as SendToken).Packet = null;

                                if (CanSendPacket(e, true))
                                {
                                    repeat = true;
                                }
                                break;
                            default:
                                throw new InvalidOperationException(e.LastOperation.ToString());
                        }
                    }
                    else
                        throw new InvalidOperationException(e.LastOperation.ToString());
                } while (repeat);
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }
        private void IOCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                bool repeat;
                do
                {
                    repeat = false;

                    if (e.SocketError != SocketError.Success)
                    {
                        throw new SocketException((int)e.SocketError);
                    }

                    if (e.LastOperation == SocketAsyncOperation.Receive)
                    {
                        switch (receiveState)
                        {
                        case ReceiveState.ReceivingHdr:
                            if (e.BytesTransferred < 5)
                            {
                                parent.Disconnect();
                                return;
                            }

                            if (e.Buffer[0] == 0x3c && e.Buffer[1] == 0x70 &&
                                e.Buffer[2] == 0x6f && e.Buffer[3] == 0x6c && e.Buffer[4] == 0x69)
                            {
                                ProcessPolicyFile();
                                return;
                            }

                            var len = (e.UserToken as ReceiveToken).Length =
                                IPAddress.NetworkToHostOrder(BitConverter.ToInt32(e.Buffer, 0)) - 5;
                            if (len < 0 || len > BUFFER_SIZE)
                            {
                                throw new InternalBufferOverflowException();
                            }
                            (e.UserToken as ReceiveToken).Packet = Packet.Packets[(PacketID)e.Buffer[4]].CreateInstance();

                            receiveState = ReceiveState.ReceivingBody;
                            e.SetBuffer(0, len);
                            if (!skt.ReceiveAsync(e))
                            {
                                repeat = true;
                                continue;
                            }
                            break;

                        case ReceiveState.ReceivingBody:
                            if (e.BytesTransferred < (e.UserToken as ReceiveToken).Length)
                            {
                                parent.Disconnect();
                                return;
                            }

                            var pkt = (e.UserToken as ReceiveToken).Packet;
                            pkt.Read(parent, e.Buffer, (e.UserToken as ReceiveToken).Length);

                            receiveState = ReceiveState.Processing;
                            bool cont = OnPacketReceived(pkt);

                            if (cont && skt.Connected)
                            {
                                receiveState = ReceiveState.ReceivingHdr;
                                e.SetBuffer(0, 5);
                                if (!skt.ReceiveAsync(e))
                                {
                                    repeat = true;
                                    continue;
                                }
                            }
                            break;

                        default:
                            throw new InvalidOperationException(e.LastOperation.ToString());
                        }
                    }
                    else if (e.LastOperation == SocketAsyncOperation.Send)
                    {
                        switch (sendState)
                        {
                        case SendState.Ready:
                            var dat = (e.UserToken as SendToken).Packet.Write(parent);

                            sendState = SendState.Sending;
                            e.SetBuffer(dat, 0, dat.Length);
                            if (!skt.SendAsync(e))
                            {
                                repeat = true;
                                continue;
                            }
                            break;

                        case SendState.Sending:
                            (e.UserToken as SendToken).Packet = null;

                            if (CanSendPacket(e, true))
                            {
                                repeat = true;
                                continue;
                            }
                            break;

                        default:
                            throw new InvalidOperationException(e.LastOperation.ToString());
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException(e.LastOperation.ToString());
                    }
                } while (repeat);
            }
            catch (Exception ex)
            {
                OnError(ex);
            }
        }