EndRead() public method

public EndRead ( IAsyncResult asyncResult ) : int
asyncResult IAsyncResult
return int
Beispiel #1
0
 private void ReadNetworkData(NetworkStream stream)
 {
     try
     {
         stream.BeginRead(_buffer, 0, _buffer.Length, ar =>
         {
             ParseBuffer(stream.EndRead(ar));
             ReadNetworkData(stream);
         }, stream);
     }
     catch
     {
     }
 }
Beispiel #2
0
		private int Read(NetworkStream stream, byte[] buffer, int count)
		{
			var ar = stream.BeginRead(buffer, 0, count, null, null);
			if (!ar.AsyncWaitHandle.WaitOne(SocksTimeout))
			{
				throw new SocksException("The proxy did not respond in a timely manner.");
			}
			count = stream.EndRead(ar);
			if (count < 2)
			{
				throw new SocksException("Unable to negotiate with the proxy.");
			}
			return count;
		}
Beispiel #3
0
        private static string GetResponse(NetworkStream stream, out string response)
        {
            byte[] readBuffer = new byte[32];
            var asyncReader = stream.BeginRead(readBuffer, 0, readBuffer.Length, null, null);
            WaitHandle handle = asyncReader.AsyncWaitHandle;

            // Give the reader 2seconds to respond with a value
            bool completed = handle.WaitOne(1000, false);
            if (completed)
            {
                int bytesRead = stream.EndRead(asyncReader);

                StringBuilder message = new StringBuilder();
                message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));

                if (bytesRead == readBuffer.Length)
                {
                    // There's possibly more than 32 bytes to read, so get the next
                    // section of the response
                    string continuedResponse;
                    if (GetResponse(stream, out continuedResponse) != "")
                    {
                        message.Append(continuedResponse);
                    }
                }

                response = message.ToString();
                return response;
            }
            else
            {
                int bytesRead = stream.EndRead(asyncReader);
                if (bytesRead == 0)
                {
                    // 0 bytes were returned, so the read has finished
                    response = string.Empty;
                    return response;
                }
                else
                {
                    StringBuilder message = new StringBuilder();
                    message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));

                    if (bytesRead == readBuffer.Length)
                    {
                        // There's possibly more than 32 bytes to read, so get the next
                        // section of the response
                        string continuedResponse;
                        if (GetResponse(stream, out continuedResponse) != "")
                        {
                            message.Append(continuedResponse);
                        }
                    }

                    response = message.ToString();
                    return response;
                }
            }
        }
Beispiel #4
0
        public static Message Read(NetworkStream stream, int timeout)
        {
            Message message = null;

            try
            {
                //Read length of the message
                var lengthBytes = new byte[4];
                var asyncResult = stream.BeginRead(lengthBytes, 0, lengthBytes.Length, null, null);

                //Wait for result or timeout
                asyncResult.AsyncWaitHandle.WaitOne(timeout);

                if(asyncResult.IsCompleted)
                {
                    int alreadyRead = stream.EndRead(asyncResult);
                    message = Read(stream, lengthBytes, alreadyRead);
                }
            }
            catch { }

            return message;
        }
        protected override EventWaitHandle DoLoopInner(NetworkStream ns, TransferState ts)
        {
            byte[] bufferread = new byte[1024*1];
            byte[] bufferwrite =null;
            int count;

            ManualResetEvent mreDone = new ManualResetEvent(false);

            AsyncCallback readcallback=null;

            readcallback = ar_c =>
            {
                try
                {
                    count = ns.EndRead(ar_c);
                    ts.AddReadBytes(count);
            #if VERBOSE
                    //if (ts.totalreadbytes % 10000 == 0) ConsoleLogger.LogMessage("read: " + ts.totalreadbytes);
            #endif
                    bool EOFPresent = false;
                    if (count > 0)
                    {

                        EOFPresent = HandleBuffer(bufferread, count, answer, out bufferwrite);
                        ns.Write(bufferwrite, 0, bufferwrite.Length);

                        if (bufferwrite != null)
                        {
                            ts.AddWriteBytes(bufferwrite.Length);
                        }
                    }

                    if (EOFPresent == false && count>0)
                    {
                        ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts);
                    }
                    else
                    {
                        mreDone.Set();
                    }
                }
                catch (IOException ioe)
                {
                    if (ioe.InnerException != null)
                    {
                        SocketException se = ioe.InnerException as SocketException;
                        if (se != null)
                        {
                            if (se.SocketErrorCode == SocketError.ConnectionReset)
                            {
                                ConsoleLogger.LogMessage("Client closed connection!");
                                mreDone.Set();
                                return;
                            }
                        }
                        ObjectDisposedException ode = ioe.InnerException as ObjectDisposedException;
                        if (ode != null)
                        {
                            ConsoleLogger.LogMessage("Client closed connection.");
                            mreDone.Set();
                            return;
                        }
                    }
                    throw ioe;
                }
                catch (Exception ex)
                {
                    ConsoleLogger.LogMessage("Error in readcallback: " + ex.ToString());
                    mreDone.Set();
                }
            };

            //начинаем асинхронное чтение данных
            ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts);

            //ожидаем завершения обработки
            mreDone.WaitOne();

            //обработка завершена
            ConsoleLogger.LogMessage("Thread shutdown!");
            return mreDone;
        }
Beispiel #6
0
        private bool Connect()
        {
            try
                {
                TCPClient = new TcpClient(IPAddress, PortNumber);
                }
            catch (Exception exc)
                {
                Console.WriteLine("Can't connect: " + exc.Message);
                return false;
                }

            String ConnResult = "";

            try
                {
                TCPStream = TCPClient.GetStream();
                byte[] StreamTest = new byte[10];

                IAsyncResult NetStreamReadRes = TCPStream.BeginRead(StreamTest, 0, StreamTest.Length, null, null);

                if (NetStreamReadRes.AsyncWaitHandle.WaitOne(1500, false))
                    {

                    int streamLength = TCPStream.EndRead(NetStreamReadRes);
                    ConnResult = Encoding.GetEncoding(1251).GetString(StreamTest, 0, streamLength);
                    }
                }
            catch (Exception exc)
                {
                Console.WriteLine("Can't create the network stream: " + exc.Message);
                return false;
                }
            if (ConnResult != "$M$_$ERVER") return false;

            SetConnectionStatus(true);
            if (Client.User != 0)
                {
                PackageViaWireless Package = new PackageViaWireless(0, true);
                Package.DefineQueryAndParams("ConnectionRecovery", "");
                Package.ClientCode = Client.User;
                SendPackage(Package.GetPackage());
                }
            // Запуск пинга сервера

            //PingAgent = new CallTimer(PingServer, 500);
            return true;
        }
        // #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #
        private bool Connect()
        {
            try
                {
                TCPClient = new TcpClient(IPAddress, PortNumber);
                }
            catch ( Exception exp )
                {
                Console.WriteLine("Can't connect: " + exp.Message);

                return false;
                }

            String ConnResult = "";

            try
                {
                TCPStream = TCPClient.GetStream();
                byte[] StreamTest = new byte[10];

                IAsyncResult NetStreamReadRes = TCPStream.BeginRead(StreamTest, 0, StreamTest.Length, null, null);

                if ( NetStreamReadRes.AsyncWaitHandle.WaitOne(3000, false) )
                    {
                    int streamLength = TCPStream.EndRead(NetStreamReadRes);
                    NetStreamReadRes = null;
                    ConnResult = Encoding.GetEncoding(1251).GetString(StreamTest, 0, streamLength);
                    }
                else
                    {
                    System.Diagnostics.Trace.WriteLine("Не получил ответа о сервере");
                    }
                }
            catch ( Exception exp )
                {
                Console.WriteLine("Can't create the network stream: " + exp.Message);
                return false;
                }
            if ( ConnResult != "$M$_$ERVER" ) return false;

            SetConnectionStatus(true);

            // Запуск пинга сервера

            //PingAgent = new CallTimer(PingServer, 500);
            Console.WriteLine("Соединение установлено");
            return true;
        }
Beispiel #8
0
        private void OnReadFromTcp(IAsyncResult ar)
        {
            int read = 0;

            try
            {
                read = m_tcpStream.EndRead(ar);
            }
            catch (Exception)
            {
                OnPipeDead(EventArgs.Empty);
                return;
            }

            if (0 == read)
            {
                OnPipeDead(EventArgs.Empty);
                return;
            }

            if (read != m_tcpBuffer.Length)
            {
                throw new SipProxyException("Unexpected length of header read from TCP.");
            }

            bool sip = true, rtp = true;

            for (byte i = 0; i < g_TcpSipPacketTag.Length; i++)
            {
                sip = sip && (m_tcpBuffer[i] == g_TcpSipPacketTag[i]);
                rtp = rtp && (m_tcpBuffer[i] == g_TcpRtpPacketTag[i]);
            }

            if (sip == rtp)
            {
                throw new SipProxyException("Unrecognized packet read from TCP.");
            }

            ushort dataLen = BitConverter.ToUInt16(m_tcpBuffer, g_TcpSipPacketTag.Length);

            byte[] myBuff = new byte[dataLen];

            int readTotal = 0;

            while (readTotal < dataLen)
            {
                read       = m_tcpStream.Read(myBuff, readTotal, myBuff.Length - readTotal);
                readTotal += read;
            }

            if (sip)
            {
                OnSipReceivedFromTcp(
                    new SipMessageEventArgs(g_Ascii.GetString(myBuff, 0, myBuff.Length))
                    );
            }
            else
            {
                OnRtpReceivedFromTcp(
                    new RtpMessageEventArgs(myBuff)
                    );
            }

            try
            {
                m_tcpStream.BeginRead(m_tcpBuffer, 0, m_tcpBuffer.Length, OnReadFromTcp, null);
            }
            catch (Exception)
            {
                OnPipeDead(EventArgs.Empty);
            }
        }
Beispiel #9
0
        internal void ReceiveDataAndEnqueue()
        {
            log.Context = MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name;
            log.WriteLog("Received Data and Enqueue thread started");
            string s;
            int iCRat, iCRcount;
            string[] sa;
            int length = 0;
            string sLastErrorMessage = "";
            while (!m_bDone)
            {
                if (m_ConnectionErrorOccurred)
                {
                    continue;
                }
                try
                {
                    try
                    {
                        m_TCPClient.ReceiveTimeout = 100;
                        m_NetworkStream = m_TCPClient.GetStream();
            //						m_NetworkStream.Read(m_bytesIncomingBuffer,m_iBufferLength,m_iBufferMaxLength -	m_iBufferLength);
                        IAsyncResult asr = m_NetworkStream.BeginRead(m_bytesIncomingBuffer, m_iBufferLength, m_iBufferMaxLength -
                                                                                                             m_iBufferLength, null, null);
                        while (!asr.IsCompleted && !m_bDone)
                        {
                            Thread.Sleep(100);
                        }
                        if (m_bDone)
                        {
                            continue;
                        }
                        length = m_NetworkStream.EndRead(asr);
                    }
                    catch (IOException ioex)
                    {
                        if (null != ioex.InnerException)
                        {
                            if (ioex.InnerException is SocketException)
                            {
                                int iErrorCode = ((SocketException) ioex.InnerException).ErrorCode;
            //								if (iErrorCode == 10060)
            //								{	// read timeout... just continue
            //									//TODO: This doesn't work in .NET 2.0!!! Must change implementation!
            //									continue;
            //								}
                                string sErrorMessage = ioex.InnerException.Message;
                                sLastErrorMessage = "ReceiveDataAndEnqueue: Error Code = " + iErrorCode.ToString() + " Description = " +
                                                    sErrorMessage;
                            }
                            else
                            {
                                sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ioex.Message;
                            }
                        }
                        log.WriteLog(sLastErrorMessage);
                        m_bDone = true;
                        m_bConnected = false;
                    }
                    catch (Exception ex)
                    {
                        sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ex.Message;
                        log.WriteLog(sLastErrorMessage);
                        m_bDone = true;
                        m_bConnected = false;
                    }

                    if (!m_bConnected)
                    {
                        OnConnectionErrorReceived(this, sLastErrorMessage);
                        continue;
                    }
                    if (m_bDone)
                        continue;

                    if (0 == length)
                    {
                        // connection must have been reset
                        m_bDone = true;
                        continue;
                    }

                    m_iBufferLength += length;

                    // find all the messages in the stream
                    iCRcount = 0;
                    for (int i = 0; i < m_iBufferLength; i++)
                    {
                        if (m_bytesIncomingBuffer[i] == 13)
                            iCRcount++;
                    } // for
                    // post all messages from the stream
                    for (int i = 0; i < iCRcount; i++)
                    {
                        s = Encoding.ASCII.GetString(m_bytesIncomingBuffer);
                        s = s.Substring(0, m_iBufferLength);
                        iCRat = s.IndexOf((char) 13);
                        if (-1 != iCRat)
                        {
                            int iLen;
                            s = s.Substring(0, iCRat);
                            iLen = s.Length + 1;
                            m_iBufferLength -= iLen;
                            //m_sLastResponse = s;
                            lock (m_qCommands.SyncRoot)
                            {
                                Command cmd;
                                string[] saParams;
                                sa = Command.DecodeCommand(Encoding.ASCII.GetBytes(s), s.Length);
                                if (sa.Length > 1)
                                {
                                    saParams = new string[sa.Length - 1];
                                    Array.Copy(sa, 1, saParams, 0, sa.Length - 1);
                                    cmd = new Command(sa[0], saParams);
                                }
                                else
                                {
                                    cmd = new Command(sa[0], null);
                                }
                                m_qCommands.Enqueue(cmd);
                                log.WriteLog("Command Enqueued: " + cmd.VerbString);
                            }
                            byte[] bytes = new byte[m_iBufferLength];
                            Array.Copy(m_bytesIncomingBuffer, 0, bytes, 0, m_iBufferLength);
                            OnMessageReceived(new CommandEventArgs(bytes, ref m_qCommands));
                            Array.Copy(m_bytesIncomingBuffer, iLen, m_bytesIncomingBuffer, 0, m_iBufferLength);
                            Array.Clear(m_bytesIncomingBuffer, m_iBufferLength, m_iBufferMaxLength - m_iBufferLength);
                        } // if
                    } // for
                }
                catch (Exception ex)
                {
                    log.WriteLog("Unknown Error detected. Description = " + ex.Message);
                }
            } // while
            m_EventThreadComplete[0].Set();
        }
Beispiel #10
0
        private void ReadCallback(IAsyncResult result)
        {
            int length = 0;
            try
            {
                _stream = _client.GetStream();
                if (_stream != null)
                    length = _stream.EndRead(result);
            }
            catch
            {
                Log.Error("Lost connection from loginserver");
                return;
            }

            if (length == 0)
            {
                return;
            }

            byte[] data = new byte[length];
            Buffer.BlockCopy(_buffer, 0, data, 0, length);

            HandlePacket(data);

            _stream.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, _buffer);
        }