在Tomcat上连接套接字?

时间:2011-06-18 12:56:42

标签: java eclipse sockets 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) { 
            }
        }
    }

我已经将这个部署到了TomCat。我的问题是我的applet需要将套接字设置为什么地址?当i visit http://localhost:8080/scrabServ/connect我看到来自doGet()的“RUNNING”消息时,它是否需要指向哪里?

小程序:

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)行。

1 个答案:

答案 0 :(得分:2)

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

要通过请求参数与servlet通信,基本上发出GET命令,例如:http://www.jmarshall.com/easy/http/http_footnotes.html#getsubmit

也许您应该使用URLConnection代替。如果你详细说明你想要做什么,也许我可以更好地了解如何帮助你,甚至可能甚至不需要HTTP服务器。