Пример #1
0
        private static void OnReceiveMessage(MessageReceivedEventArgs e)
        {
            var message = e.Message;
            Console.WriteLine("{0} =={2}==> {1}: {3}", message.Source, message.Target, message.Type, Encoding.UTF8.GetString(message.Data));

            if(message.Type == MessageType.Request)
                e.Reply(Encoding.UTF8.GetBytes("Reply for Hello World"));
        }
Пример #2
0
        private void ReadCallback(IAsyncResult result)
        {
            try
            {
                int totalRead = m_Stream.EndRead(result);
                var lengthBytes = result.AsyncState as byte[];

                if(totalRead > 0)
                {
                    //Read the full message
                    var message = Message.Read(m_Stream, lengthBytes, totalRead);

                    //Pass to handler
                    if(OnReceiveMessage != null)
                    {
                        var args = new MessageReceivedEventArgs(m_Stream, message);
                        OnReceiveMessage(args);
                    }

                    //Read again
                    Array.Clear(lengthBytes, 0, lengthBytes.Length);
                    m_Stream.BeginRead(lengthBytes, 0, lengthBytes.Length, new AsyncCallback(ReadCallback), lengthBytes);
                }
                else
                {
                    //Connection closed, notify handler
                    if(OnLoseConnection != null)
                        OnLoseConnection();
                }
            }
            catch
            {
                //Connection broken, notify handler
                if(OnLoseConnection != null)
                    OnLoseConnection();
            }
        }