I need to send UDP packets out from my application. Is it possible to use java.net.DatagramSocket as a resource reference so that I have just one UDP socket created for the entire application?
I'm not familiar with a Resource Reference. I dug up something on Tomcat 4.0 but I haven't used Tomcat 4 and from the looks of it, it's Tomcat specific. If that's what you're talking about you might want to ask on Tomcat list.
Optionally you could store it in an application session object.
Basically the rule of thumb on network connections can be shared as long as you don't have to serialize them.
One thing to remember with UDP is that it does not ensure packets are in any order. It just sends them. If that's important, use TCP or higher level application protocol (like HTTP, SMTP, etc).
If you're passing messages you might want to check out JMS.
Unfortunately, I need to use the UDP socket in the EJB layer, not the servlet layer; there is no "application session object" here.
Resource references allow you to reference "resources" that EJBs need, such as JavaMail or database connection pools. I am wondering whether it is possible (and spec-compliant) to bind a UDP socket here so that I can look one up and then use it.
Got ya. I've got a similar situation with the application I'm writing now.
In theory you can reference anything, all the data pooling does in the app servers is simply provide wrappers around standard stuff.
To my knowledge most application servers don't allow you to do this on your own. The only potential possibility would be JBoss because of it's open source nature.
The only trick that I know of is to make the connection static in the EJB. I don't think that's complete to the spec but it takes into account the fact that EJBs are Java and most app servers keep an instance pool (objects cached in memory to speed up execution).
If you find anything different, please post. Like I said, I know I could benefit from it, and I'm sure others could.
To repeat the question to everyone:
Can a java.net.DatagramSocket be used as a resource reference for EJBs?
No. Not portably. Not even "theoreticaly". Theoreticaly you can only access resource that the EJB spec lists. And UDP sockets are not one of them.
Some App servers may allow this as a proprietary extension (I am not aware of any such servers).
Maybe you can wrap your Socket connection as a resource manager connection factory, then declare a such reference in your EJB, and invoke it just like the JDBC connection example in EJB 2.0 spec chapter 20.4.
But I never did it and don't know if it would work or it's the best way to do it.
Hope this helps and Let me know if it works