sleiva112
sleiva112

Reputation: 21

TCP connections and Tomcat

I need to configure Tomcat 5.5 to receive direct TCP connections (instead of receiving HTTP connections).

The idea is to receive TCP connections from a client and store the information in a database.

Can you help?

Upvotes: 1

Views: 3471

Answers (2)

Stefan
Stefan

Reputation: 12462

While I think EJP is right, Tomcat is indended to serve http connections, here is a basic approach with a listener:

package test;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ServerSocketListener implements ServletContextListener {

     private ServerSocket serverSocket;
     private final int PORT = 8081;

     @Override
     public void contextInitialized(ServletContextEvent sce) {
            System.out.println("Starting server socket at port: " + PORT);
            try {
                 serverSocket = new ServerSocket(PORT);
                 while (true) {
                      Socket client = serverSocket.accept();
                      System.out.println("Client connected from: "+client.getInetAddress().getHostAddress());
                      //handle connection ...
                 }
            } catch (IOException e) {
                 e.printStackTrace();
            }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
         try {
             if(serverSocket!=null) {
                 System.out.println("Stopping server socket at port: " + PORT);
                 serverSocket.close();
             }
         } catch (IOException e) {
              e.printStackTrace();
         }
     }
 }

In your web.xml add these lines:

<listener>
     <listener-class>test.ServerSocketListener</listener-class>
</listener>

Then take your mobile and hit: http://[Server-ip]:8081/ .

Upvotes: 0

user207421
user207421

Reputation: 311023

Your question embodies a contradiction in terms. Tomcat is a servlet container; servlets speak HTTP. You could always open a ServerSocket inside a Servlet or a ServletContextListener, but then what do you actually need Tomcat for at all?

Upvotes: 2

Related Questions