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.
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.
You can do all that, just write the code, but why do you need the servlet part? or Tomcat?
Definitely check out servlet for implementing socket connection. What you are trying to do is non-standard.
I wanted to use some servlet container (like Tomcat), because i will use WebServices (as a client and server) too.
精彩评论