Example #1
0
        private void readCallback(IAsyncResult ar)
        {
            try
            {
                netStream.EndRead(ar);
                NetworkMessage netMesasge = new NetworkMessageFormatter <NetworkMessage>().Deserialize(ar.AsyncState as byte[]);
                if (netMesasge != null)
                {
                    ReadCompleted?.BeginInvoke(this, new NetworkMessageReaderReadCompletedEventArgs(netMesasge, TcpClient), null, null);
                }
                else
                {
                    ReadError?.BeginInvoke(this, new NetworkMessageErrorEventArgs(TcpClient, new ArgumentNullException("NetworkMessage is null")), null, null);
                }

                if (readLoop)
                {
                    ReadAsync(readLoop);
                }
            }
            catch (Exception ex)
            {
                ReadError?.BeginInvoke(this, new NetworkMessageErrorEventArgs(TcpClient, ex), null, null);

                if (OnErrorStopReadingAndCloseClient)
                {
                    netStream?.Close();
                    TcpClient?.Close();

                    ReadCompleted = null;
                    ReadError     = null;
                }
            }
        }
Example #2
0
        public void WriteAsync(NetworkMessage netMessage)
        {
            byte[] buffer = new NetworkMessageFormatter <NetworkMessage>().Serialize(netMessage);

            TcpClient.SendBufferSize = buffer.Length;
            netStream = TcpClient.GetStream();
            if (netStream.CanWrite)
            {
                netStream.BeginWrite(buffer, 0, buffer.Length, writeCallback, netMessage);
            }
            else
            {
                throw new Exception("NetworkStream can not write");
            }
        }