๐Ÿ™‡โ€โ™€๏ธRecvBuffer

๐Ÿช๋ถ„์„

TCP์ •์ฑ…์—์„  100๋ฐ”์ดํŠธ๋ฅผ ๋ณด๋‚ด๋ฉด ๋ฌด์กฐ๊ฑด 100๋ฐ”์ดํŠธ๋ฅผ ๋ฐ›๋Š”๋‹ค๊ณ  ํ•  ์ˆ˜ ์—†๋‹ค. 80๋ฐ”์ดํŠธ๋งŒ ์˜ฌ์ˆ˜์žˆ๋Š”๋ฐ ์ด๋Ÿฐ ๊ฒฝ์šฐ ๋‚˜๋จธ์ง€ 20๋ฐ”์ดํŠธ๋ฅผ ์ถ”๊ฐ€๋กœ ๋ฐ›๊ณ  ์™„์„ฑ๋œ ํŒจํ‚ท์„ ๋ณด๋‚ด์•ผ ํ•œ๋‹ค.

RecvBuffer์—์„œ๋Š” ์ด๋Ÿฌํ•œ ๋ถ€๋ถ„์„ ๋‹ค๋ฃฐ ๊ฒƒ์ด๋‹ค.

_readPos - ์ฝ๊ธฐ ์ปค์„œ ์œ„์น˜ _writePos - ์“ฐ๊ธฐ ์ปค์„œ ์œ„์น˜

Recv์ƒ์„ฑ์ž - BufferSize๋ฅผ ์ •ํ•ด Buffer๋ฅผ ๋งŒ๋“ค์–ด์คŒ

DataSize - ์‚ฌ์šฉํ•œ ๋ฐ์ดํ„ฐ FreeSize - ๋‚จ์€ ๋ฐ์ดํ„ฐ ๊ณต๊ฐ„

ReadSegment - ์ฝ๊ธฐ ์ปค์„œ๋ถ€ํ„ฐ DataSize๋งŒํผ์˜ ArraySegment๋ฅผ ๋ฐ˜ํ™˜ WriteSegment - ์“ฐ๊ธฐ ์ปค์„œ๋ถ€ํ„ฐ ๋‚จ์€ ๊ณต๊ฐ๊นŒ์ง€์˜ ArraySegment๋ฅผ ๋ฐ˜ํ™˜

Clean - ์šฐ๋ฆฌ๊ฐ€ ๋งŒ๋“  ๋ฒ„ํผ๋ฅผ ๋‹ค์“ธ ๋•Œ ์ดˆ๊ธฐํ™” ์‹œ์ผœ์ฃผ๋Š” ํ•จ์ˆ˜, ๋”ฑ ์•Œ๋งž๊ฒŒ ์“ฐ๋ฉด ์ฝ๊ธฐ ์ปค์„œ์™€ ์“ฐ๊ธฐ ์ปค์„œ๋ฅผ 0์œผ๋กœ ์ด๋™, ๊ทธ๋ ‡์ง€ ์•Š๊ณ  ์ฐŒ๋„๋ ˆ๊ธฐ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ DataSize๋งŒํผ ๋ณต์‚ฌํ•˜์—ฌ ์ฒซ ์œ„์น˜๋กœ ์ด๋™ ์‹œํ‚จ ํ›„ ์ฝ๊ธฐ ์ปค์„œ๋Š” 0 ์“ฐ๊ธฐ ์ปค์„œ๋Š” DataSize๋งŒํผ ์ด๋™

OnRead - ์ฝ๊ธฐ ์ปค์„œ ์ด๋™ OnWrite - ์“ฐ๊ธฐ ์ปค์„œ ์ด๋™

๐Ÿช์ „์ฒด์ฝ”๋“œ

namespace ServerCore
{
    public class RecvBuffer
    {
        // [r][w][ ][ ][ ][ ][ ][ ]
        ArraySegment<byte> _buffer;
        int _readPos;
        int _writePos;

        public RecvBuffer(int bufferSize)
        {
            _buffer = new ArraySegment<byte>(new byte[bufferSize], 0, bufferSize);
        }

        public int DataSize { get { return _writePos - _readPos; } }
        public int FreeSize { get { return _buffer.Count - _writePos; } }

        public ArraySegment<byte> ReadSegment
        {
            get { return new ArraySegment<byte>(_buffer.Array, _buffer.Offset + _readPos, DataSize); }
        }

        public ArraySegment<byte> WriteSegment
        {
            get { return new ArraySegment<byte>(_buffer.Array, _buffer.Offset + _writePos, FreeSize); }
        }

        public void Clean()
        {
            int dataSize = DataSize;
            if (dataSize == 0)
            {
                // ๋‚จ์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์œผ๋ฉด ์‹œ์ž‘ ์œ„์น˜๋กœ ์ปค์„œ๋งŒ ์ด๋™
                _readPos = _writePos = 0;
            }
            else
            {
                // ๋‚จ์€ ์ฐŒ๋„๋ ˆ๊ธฐ๊ฐ€ ์žˆ์œผ๋ฉด ์‹œ์ž‘ ์œ„์น˜๋กœ ๋ณต์‚ฌ
                Array.Copy(_buffer.Array, _buffer.Offset + _readPos, _buffer.Array, _buffer.Offset, DataSize);
                _readPos = 0;
                _writePos = dataSize;
            }
        }

        public bool OnRead(int numOfBytes)
        {
            if (numOfBytes > DataSize)
                return false;

            _readPos += numOfBytes;
            return true;
        }

        public bool OnWrite(int numOfBytes)
        {
            if (numOfBytes > FreeSize)
                return false;

            _writePos += numOfBytes;
            return true;
        }
    }
}

ํƒœ๊ทธ:

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ: