/// <summary> /// ストリームから同期読み取りを行います。 /// </summary> /// <remarks> /// エラー等の場合はnullを返します。 /// </remarks> private byte[] ReadBytes(Stream stream, BinarySplitReader reader) { try { // すでに読み込まれたデータがあるならそれを返します。 var bytes = reader.ReadUntil((byte)'\n'); if (bytes != null) { return(bytes); } var buffer = new byte[256]; var size = stream.Read(buffer, 0, buffer.Length); if (size == 0) { // ソケットが閉じられたときはnullを返します。 return(null); } reader.Write(buffer, 0, size); return(reader.ReadUntil((byte)'\n') ?? new byte[0]); } catch (Exception ex) { Util.ThrowIfFatal(ex); Log.ErrorException(ex, "ソケットの受信処理に失敗しました。"); return(null); } }
/// <summary> /// サーバーへの接続、受信、送信などの中継処理を行います。 /// </summary> private void ProxyThread(object state) { var data = (ThreadData)state; var timer = new Stopwatch(); BinarySplitReader reader = null; this.streams[data.Index] = CreateStream(data); timer.Start(); while (!Aborted) { if (reader == null) { reader = new BinarySplitReader(2048); } var stream = this.streams[data.Index]; if (stream == null || !stream.CanRead) { if (Aborted) { break; } else if (timer.Elapsed < TimeSpan.FromSeconds(5)) { continue; } this.streams[data.Index] = CreateStream(data); timer.Restart(); continue; } var bytes = ReadBytes(stream, reader); if (bytes == null) { Log.Info("{0}: disconnected", data.Name); // 戻り値がnullの場合はストリームを閉じます。 CloseStreams(); reader = null; continue; } if (!bytes.Any()) { continue; } // コンソールに出力 WriteLog(data, bytes); // 書き込み先ソケットに出力します。 WriteBytes(this.streams[data.CoIndex], bytes); } }
/// <summary> /// コンストラクタ /// </summary> public AlertClient() { //this.stream = new MemoryStream(); this.reader = new BinarySplitReader(2048); }