Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java custom event handler and listeners

I'm currently playing around with a Java implementation of Socket.io, available here: netty-socketio

I've got the server up and running, and its receiving/sending messages nicely between client and server, but I need to have events trigger on certain messages being received, and that's where I'm confused.

Here's my code:

server.addEventListener("message", clientData.class, new DataListener<clientData>() {
    @Override
    public void onData(SocketIOClient client, clientData data, AckRequest ackRequest) throws Exception {
                System.out.println("Message from client: " + data.getMessage());

    }
});


public class ClientData{

    String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

Essentially what I'd like to happen is when a particular message is received from a client, I need a function within another class to run. I've spent the last two hours reading about Observable, Observer, Interfaces and event handlers, but I'm really not sure how to set this up.

The library also makes mention of this DataListener, but I've no idea what that is, as there's little documentation in the library.

Any input or advice on this would be greatly appreciated.

like image 664
Tony Avatar asked Nov 27 '15 00:11

Tony


1 Answers

Let's say your class that raises the event is called A. And the class that needs to listen for the event is called B. And the event is called SomeEvent.

First, create an interface called SomeEventListener:

public interface SomeEventListener {
    void onSomeEvent ();
}

If there are arguments that you want to pass when the event occurs (typically something about the event), you can add it to the method.

Then in A, you add a field:

private SomeEventListener listener;

and a method:

public void setSomeEventListener (SomeEventListener listener) {
    this.listener = listener;
}

This way, B can call setSomeEventListener to set the listener.

When the event occurs, A should call

if (listener != null) listener.onSomeEvent ();

And that's all there is to A!

In B, you need to implement the interface:

public class B implements SomeEventListener {
    public void onSomeEvent () {
        //do whatever you like when SomeEvent happens.
    }
}

And you can listen for SomeEvent like this:

someInstanceOfA.setSomeEventListener (this);

And after this call, all the SomeEvent raised by A can be listened by B!

Using the Observable and Observer pattern, we can see that A is an Observable and B is an Observer.

That's easy!

like image 96
Sweeper Avatar answered Oct 06 '22 00:10

Sweeper