How do I implement a web application with a Servlet that is listening on a port for socket connections?
-
1btw, what language is the remote client written in? If you are using Java in the remote client, it might be better to use RMI or even remote EJB calls. – Vineet Reynolds Aug 30 '09 at 18:35
-
Yes! the client is written in Java. – Kevin Boyd Aug 31 '09 at 04:39
3 Answers
Having the servlet open ServerSockets is a bad code smell. This is primarily because it is the container's responsibility to manage sockets (among other resources like worker threads, sessions etc).
That said, I do not think you need a servlet in the first place. Unless you want to access some of the container's services, it would be better if you use a J2SE application to manage ServerSockets.

- 76,006
- 17
- 150
- 174
-
What would I then need to implement this? Any code example? I have looked in client/server example posted above. Is that the way to go? – Kevin Boyd Aug 30 '09 at 18:36
-
1"It Depends!!". It is easy to come up with a server application using J2SE, as long as you dont botch up anything related to what a J2EE/JEE container provides out of the box. If you ever have to deal with transaction management, state management, thread pools etc., take a look at a HTTP based message exchange format, and use servlets. Eventually, it is depends on what you need your server to do. – Vineet Reynolds Aug 30 '09 at 18:42
I assume you don't mean the front-door HTTP connection, which you get for free with the servlet container... But if you want to add, say, an admin service you could create a listener thread that sets some global state in the servlet. Note that this is not considered kosher (and I believe may even violate the servlet standard).

- 7,003
- 5
- 36
- 54
-
I have a remote client and would not like to use HTTP but TCP sockets to connect to my server, therefore I would like my servlet to create some kind of serverSocket and listen for client requests for socket connections. – Kevin Boyd Aug 30 '09 at 18:23
-
2Servlets are very specifically an HTTP standard. If you don't want HTTP, you shouldn't use servlets - just write a custom client/server application, as Helen suggets. – G__ Aug 30 '09 at 18:43
-
1
Not totally sure what you want to achieve, but you can have a look at client/server programming if that's what you need. Other than that, you could implement your web application as normal but change the default port to whatever suits your need.

- 4,666
- 8
- 40
- 64
-
Refer to my written to Greg, I need something similar to client/server programming but can I implement it with servlets or would I have to go some other way. – Kevin Boyd Aug 30 '09 at 18:25