• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

opening serverSocket From servlet

 
Monmohan Singh
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to start a server( using serversocket) from init() method of a servlet. But the problem is this call(to accept) blocks and the init method never completes.
If I make the the class creating the server itself as a thread then the int method throws null pointer exception
e.g
========================
public class XServlet extends HttpServlet{
public void init()
{
new AServer().start();
}

}
==========================
public class AServer extends Thread{
public void run() {
ServerSocket serverSocket = null;
boolean serverON = true;
try {
serverSocket = new ServerSocket(8000);
} catch (IOException e) {
System.out.println("Could not listen on port: " + listenerPort);
e.printStackTrace();
}
while (serverON) {
System.out.println("Server waiting for document on Port: 8000");
try {
System.out.println("Blocking for a client Request");
Socket client = serverSocket.accept();
System.out.println("Accepted a client Request:" + client);
DocumentServerThread clientThread =
new DocumentServerThread(client);
clientThread.start();
} catch (IOException e1) {
e1.printStackTrace();
}
}
try {
serverSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Can anybody tell me a possible solution??
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If that init method throws a NullPointerException, it seems to me that your constructor is not working. Take that code apart into steps.
1. create the AServer object - a System.out.println in the constructor would be good.
2. set it to a low priority
3. start() the AServer - a System.out.println as the first line in run() would be good.
Bill
 
Monmohan Singh
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the help.. its working now..
is there a way to elegantly stop the server when the weblogic ( web server) goes down..
since the thread is not a deamon , I think this will run only till the servlet object remains ?
But if we explicitly want to close the server socket on servlet destroy.. I need to check if any client threads for this server are not active.. Is there a way to do that?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic