Пример #1
0
        async Task StartReading()
        {
            while (true)
            {
                var buffer = new byte[TcpMessageHeader.HeaderLength];
                int read   = 0;
                while (read < buffer.Length)
                {
                    read += await mTcpClient.GetStream().ReadAsync(buffer, read, buffer.Length - read);
                }

                var header = new TcpMessageHeader(buffer);

                buffer = new byte[header.Length];
                read   = 0;
                while (read < buffer.Length)
                {
                    read += await mTcpClient.GetStream().ReadAsync(buffer, read, buffer.Length - read);
                }
                var response = HandleMessage(header.TypeID, header.MessageID, new MemoryStream(buffer));

                if (response != null)
                {
                    await SendReliable(response, header.MessageID);
                }
            }
        }
Пример #2
0
        public async Task SendReliable(Message msg, int msgId = 0)
        {
            var msgStream = new MemoryStream();

            msg.WriteTo(msgStream);

            var msgbuffer = msgStream.ToArray();
            var header    = new TcpMessageHeader()
            {
                TypeID = mMsgDict.GetTypeID(msg.GetType()), Length = msgbuffer.Length, MessageID = msgId
            };

            msgStream = new MemoryStream();
            header.WriteTo(msgStream);
            var headerbuffer = msgStream.ToArray();

            msgStream = new MemoryStream();
            msgStream.Write(headerbuffer, 0, headerbuffer.Length);
            msgStream.Write(msgbuffer, 0, msgbuffer.Length);

            var result = msgStream.ToArray();
            await mTcpClient.GetStream().WriteAsync(result, 0, result.Length);
        }