小编典典

连接到Tomcat上的套接字?

tomcat

我正在尝试从独立的applet连接到在tomcat上运行的servlet:

Servlet

public void init(ServletConfig config) throws ServletException { 
    super.init(config);
    // Start a daemon thread 
    try { 
        daemonThread = new Daemon(this);
        daemonThread.start();
    }
    catch (Exception e) { 
    }
}

protected int getSocketPort() { 
    return 8080;
}

public void handleClient(Socket client){ 
    new ScribbleThread(this, client).start();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    StringBuffer sb = new StringBuffer();
    sb.append("<html><body bgcolor=pink text=red>");
    sb.append("<h1 align=center>RUNNING</h1><hr>");
    sb.append("</body></html>");
    out.println(sb);
    out.close();
}
}

Servlet init()创建了以下代码:

class Daemon extends Thread { 
private ServerSocket serverSocket;
private SocketServlet servlet;

public Daemon(SocketServlet servlet) { 
this.servlet = servlet;
}

public void run() { 
    try { 
        // Create a server socket to accept connections 
        serverSocket = new ServerSocket(servlet.getSocketPort());
    }
    catch (Exception e) { 
        return;
    }
    try { 
        while (true) { 
            try { 
                servlet.handleClient(serverSocket.accept());
            }
            catch (IOException ioe) { 
            }
        }
    }

我通过Eclipse将它部署到TomCat。我的问题是我的applet要将套接字插入哪个地址?当i visit http://localhost:8080/scrabServ/connect我从中看到“正在运行”消息时doGet(),它是在哪里指向?

小程序:

public static String testConnection(){
    InputStream in = null; 
    try { 
        // Make socket connection to servlet
        String servlet = new String("localhost/scrabServ/connect");
        Socket socket = new Socket(servlet, 8080);

这给了我:

Exception in testConnection()java.net.UnknownHostException: localhost/scrabServ/connect
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at scribble.Scribble.testConnection(Scribble.java:41)
at scribble.Scribble.main(Scribble.java:28)

并指向new Socket(servlet, 8080)线。


阅读 288

收藏
2020-06-16

共1个答案

小编典典

您只需要打开一个套接字即可"localhost", 8080,然后发出GET scrabServ/connect命令。您无法打开特定URL的套接字。

要与Servlet通信,您可以通过请求参数来实现,基本上是发出GET命令,例如:http
:
//www.jmarshall.com/easy/http/http_footnotes.html#getsubmit

Maybe you should use
URLConnection
instead. If you detail what exactly you want to do, maybe I can have a better
idea of how to help you, maybe a HTTP server is not even needed for what you
want to do.

2020-06-16