Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create servlet that will listen on specific port and accept TCP connections (non-https)

I need to create servlet that will listen on some specific port (like serverSocket.accept()), spawn new thread (like normal servlet) and pass socket (or just inputstream and outputstream) to my code. this connection has nothing to do with http. I need to read and write binary data to opened connection.

Is it possible with Tomcat? Where to begin ? I've searched for GenericSocket examples, but I see that servlet inheriting from GenericSocket still has to be configured in web.xml with some url-pattern - but this is http specific.

like image 866
alan Avatar asked Dec 07 '10 01:12

alan


1 Answers

When servlets were first introduced in Java many many years ago, one of the best books on servlet programming was Jason Hunter's Java Servlet Programming (published by OReilly). The book came with downloadable source code examples that included what is called the DaemonHttpServlet class which you can subclass to do exactly what you are asking about.

See this link for the source code: http://java.codefetch.com/example/qg/src/com/oreilly/servlet/DaemonHttpServlet.java

There is also a servlet that acts as an RMI server as well.

I can see why someone would see the utility of using servlets in this way; if your main app is a HTTP-based web app but some smaller portion of your app requires you to expose an RMI interface or some custom interface through raw sockets, then implementing them as servlets would make it easier to cleanly deploy your application as just a single .war or .ear file.

Hope that helps.

Update: some quick googling reveals the following:

  • http://blogs.webtide.com/gregw/entry/jetty_websocket_server
  • http://code.google.com/p/socketio-java/

So with the HTML5 WebSockets, it would seem that using Servlets for non-http(s) raw socket work does not seem to be such a non-standard use-case after all.

like image 188
tsaixingwei Avatar answered Oct 06 '22 01:10

tsaixingwei