This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Servlets and the fly likes opening serverSocket From servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "opening serverSocket From servlet" Watch "opening serverSocket From servlet" New topic
Author

opening serverSocket From servlet

Monmohan Singh
Ranch Hand

Joined: Aug 02, 2002
Posts: 82
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

Joined: Mar 22, 2000
Posts: 12809
    
    5
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

Joined: Aug 02, 2002
Posts: 82
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?
 
 
subject: opening serverSocket From servlet