I’m using naga to do some asynchronous socket programming.
However I need to be able to attach arbitrary data to the Socket objects.
For instance I have code like so:
service = new NIOService();
// Server is JSONObject
NIOSocket socket = service.openSocket(Server.getString("ip"), Server.getInt("port"));
??? Add mydata to socket
socket.listen(observer); // See class below
System.out.println(socket.mydata);// get new data
public static class Observer extends SocketObserverAdapter {
//Called when Socket makes connection
@Override
public void connectionOpened(NIOSocket socket) {
System.out.println(socket.mydata); // get data
socket.mydata = "yay!";// set data
}
}
The problem I have is that I need to both get and set data on a socket object in the Observer.connectionOpened callback, and be able to access it later.
I realize that there probably isn’t a way to just add data to the object, but what’s the best way to associate data with the object so that I can pass it around and still access (and modify) the data?
I can always recompile the class code to add the variables to the class, but that seems very hackish, which I try to stay away from.
Note: I’m fairly new to Java programming, but not to programming in general.
The two approaches that come to mind are:
Wrap the Socket in a class that carries information around
or, Maintain a
Mapthat holds the information you care about.I’d probably prefer the first. The second would be more appropriate if you need to hand
Socketinstances around themselves and can’t substitute your own class.