Beispiel #1
0
        internal static void ReadCallback(IAsyncResult ar)
        {
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            try
            {
                int bytesRead = handler.EndReceive(ar);

                DebugLog.Debug($"[{state.Id}] Reading {bytesRead} bytes from socket handler");

                if (bytesRead > 0)
                {
                    state.AddStringContent(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    if (handler.Available > 0)
                    {
                        DebugLog.Debug($"[{state.Id}] Socket handler contains {handler.Available} bytes remaining to read");
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    }
                    else
                    {
                        var content = state.ReadAndFlushStringContent();

                        Task.Run(() => logContent(content.Trim(), state.Id.ToString()));

                        DebugLog.Debug($"[{state.Id}] Socket handler connected: {handler.Connected}");
                        DebugLog.Debug($"[{state.Id}] Socket handler remaining bytes: {handler.Available}");

                        if (handler.Connected == false || handler.Available == 0)
                        {
                            DebugLog.Debug($"[{state.Id}] Shutting down socket connection");
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            DebugLog.Info($"[{state.Id}] Socket connection closed");
                        }
                        else
                        {
                            DebugLog.Debug($"[{state.Id}] Sending back around to get remaining stream content");
                            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugLog.Warn(ex, $"[{state.Id}] ReadCallback exception");
            }
        }