CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Oct 2010
    Posts
    6

    Question trouble with event/delegates to return a socket message

    Hi, guys.

    I'm hoping you can help me. I've been a coder a long time, but I just never have done anything with events and delegates. I have a rough understanding of the concept, but am having trouble using it in my particular application, which deals with socket messaging. Could someone help me plug in what goes where, in my code below?

    In my server app, which listens on a port, I have a string I need to throw back to the client using an event, but I am not sure how to do that. Here is a subset of my code:

    while (true) {
    bytes_received = listener.Receive (ref groupEP);
    string FullMsg = Encoding.Default.GetString (bytes_received, 0, bytes_received.Length);
    message = Encoding.ASCII.GetString (bytes_received, 0, bytes_received.Length);

    // I want to return message back to the client program, but am not sure how.
    ????

    }


    I have my delegate and event set up at the beginning of the code like this:

    public delegate void MessageReceivedHandler(string message);
    public event MessageReceivedHandler MessageReceived;


    So I hate to ask someone to just help me fill out this code, but I think if I could see a working example in my own code, it would make more sense to me. All the examples I find online are just too complex or specialized.

    Thanks so much for any help, guys.

    -Brian

  2. #2
    Join Date
    Oct 2010
    Posts
    6

    Re: trouble with event/delegates to return a socket message

    Okay, I think I have the basic code working. It goes something like this:


    MessageReceived += new MessageReceivedHandler (HeardIt);
    ...
    while (true) {

    // some code


    // I want to return message back to the client program, but am not sure how.
    // This is how, I think:
    MessageReceived (message);
    }

    private void HeardIt (string message) {
    Console.WriteLine ("Heard It! Message was: " + message);
    }


    HeardIt() seems to run when I expect it to (when a message is received). Does anyone know now how I can get the message back to the client? All the code above is in the server application.

  3. #3
    Join Date
    Jun 2008
    Posts
    2,477

    Re: trouble with event/delegates to return a socket message

    The basic model is to create an OnXXX method which fires the event. So, your code becomes:

    Code:
    void Poll()
    {
        while (true) 
        {
            bytes_received = listener.Receive (ref groupEP);
            string FullMsg = Encoding.Default.GetString (bytes_received, 0, bytes_received.Length);
            message = Encoding.ASCII.GetString (bytes_received, 0, bytes_received.Length);
            OnMessageReceived( message );
        }
    }
    
    protected virtual void OnMessageReceived( string message )
    {
        // if there are no subscribers 'del' will be null
        MessageReceivedHandler del = MessageReceived;
        if( del != null )
        {
            // fire the event
            del( e );
        }
    }
    On a side note:

    The typical signature for an event delegate is
    Code:
    public delegate void SomeEventHandler( object sender, SomeEventArgs e );
    Where 'sender' is the object which fired the event. Also, if you create your own EventArgs class you can use the generic EventHandler instead of creating your own. Just saves some typing:

    Code:
    class MessageReceivedEventArgs : EventArgs
    {
        public readonly string Message;
        public MessageReceivedEventArgs( string message )
        {
            Message = message;
        }
    }
    
    class MyClass
    {
        // has the signature: (object sender, MessageReceivedEventArgs e )
        public event EventHandler<MessageReceivedEventArgs> MessageReceived;
    }

  4. #4
    Join Date
    Jun 2008
    Posts
    2,477

    Re: trouble with event/delegates to return a socket message

    Quote Originally Posted by bek View Post
    Okay, I think I have the basic code working. It goes something like this:


    MessageReceived += new MessageReceivedHandler (HeardIt);
    ...
    while (true) {

    // some code


    // I want to return message back to the client program, but am not sure how.
    // This is how, I think:
    MessageReceived (message);
    }

    private void HeardIt (string message) {
    Console.WriteLine ("Heard It! Message was: " + message);
    }


    HeardIt() seems to run when I expect it to (when a message is received). Does anyone know now how I can get the message back to the client? All the code above is in the server application.
    You almost have it, look at my example.

    However, you do not handle your own events within the same class. Your client code would be the one to subscribe to the event, you just fire it from within the class.

  5. #5
    Join Date
    Jan 2010
    Posts
    1,133

    Re: trouble with event/delegates to return a socket message

    Quote Originally Posted by bek View Post
    I want to return message back to the client program, but am not sure how.
    The server/listener accepts a connection for each client, enabling you to obtain a socket that you can use to communicate back to that specific client. Just use one of the Send() methods, or SendAsync().

  6. #6
    Join Date
    Oct 2010
    Posts
    6

    Question Re: trouble with event/delegates to return a socket message

    Okay, I changed the name from MessageReceived to OnMessageReceived. I like to stay with convention--thanks for the tip.

    But I am getting a bit confused. I'm getting an error on the method signature:

    Code:
    protected virtual void OnMessageReceived(string message, string from) {
    
        // code
    }
    The error says my class already contains a definition for OnMessageReceived. It's probably coming from this line up near the top of my class:

    Code:
    public event MessageReceivedHandler OnMessageReceived;

    Should I also remove the HeardIt() method from the class? If I'm understanding correctly, I don't need it at all.

  7. #7
    Join Date
    Jun 2008
    Posts
    2,477

    Re: trouble with event/delegates to return a socket message

    So the event would remain "MessageReceived" and the method that fires the event would be called "OnWhateverTheEventNameIs", in this case, "OnMessageReceived".

  8. #8
    Join Date
    Oct 2010
    Posts
    6

    Re: trouble with event/delegates to return a socket message

    Oh, duh... I have it now. Thank you, Big Ed! It's much appreciated.

    So HeardIt goes away, and that line instead becomes:

    Code:
    OnMessageReceived += new MessageReceivedHandler (MessageReceived);

    Last question--the del(e) line below gives me an error, 'e does not exist in the current context." It doesn't know what 'e' is.


    Code:
    protected virtual void OnMessageReceived( string message )
    {
        // if there are no subscribers 'del' will be null
        MessageReceivedHandler del = MessageReceived;
        if( del != null )
        {
            // fire the event
            del( e );              // ERROR
        }
    }

  9. #9
    Join Date
    Jun 2008
    Posts
    2,477

    Re: trouble with event/delegates to return a socket message

    That's because my second example was showing how an event handler is typically written with two parameters; the object that fired the event (sender) and an event args object (e). You copied that code into your method, but the signature is wrong. Also, this line will not work and you are still handling your event from within the class that fires it, which is wrong.

    Code:
    OnMessageReceived += new MessageReceivedHandler (MessageReceived);
    OnMessaegReceived is a normal method and you cannot apply the += operator to it.

  10. #10
    Join Date
    Oct 2010
    Posts
    6

    Re: trouble with event/delegates to return a socket message

    Okay, I can see I need to go read up a bit. Thanks so much for your help today.

  11. #11
    Join Date
    Oct 2010
    Posts
    6

    Re: trouble with event/delegates to return a socket message

    Oh, just a note--I didn't copy the method with the "object, EventArgs" signature because I don't have an 'e' object anywhere in my DLL to refer to. That's one of the things I will be researching... not sure where to pull the 'e' out of the air from!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured