我試圖從一個獨立的小應用程序連接到Tomcat上運行一個servlet:連接到Tomcat上的套接字?
的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()
的'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)
線。
我讀到URLConnection是一個單一的請求,單一的響應方案。我需要一個持續的連接。你能解釋一下你的意思嗎?我如何使用GET將字符串「Test」傳遞給servlet inputStream? – Sbram
@Sbram我擴大了我的答案一點。 – Marcelo
謝謝你的幫助。我需要將多個客戶端連接到servlet,以便他們可以相互交互並通知其他人的操作。 – Sbram