1

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?

4

2 回答 2

2

你的问题体现了一个矛盾的术语。Tomcat是一个servlet容器;servlet 使用 HTTP。你总是可以在 Servlet 或 ServletContextListener 中打开一个 ServerSocket,但是你到底需要 Tomcat 做什么呢?

于 2012-07-31T10:02:32.843 回答
0

虽然我认为 EJP 是正确的,但 Tomcat 旨在服务于 http 连接,这是一个带有监听器的基本方法:

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();
         }
     }
 }

在您的 web.xml 添加这些行:

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

然后拿起你的手机并点击:http://[Server-ip]:8081/。

于 2012-07-31T15:10:09.853 回答