File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "opening serverSocket From servlet" Watch "opening serverSocket From servlet" New topic

opening serverSocket From servlet

Monmohan Singh
Ranch Hand

Joined: Aug 02, 2002
Posts: 82
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
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);
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);
} catch (IOException e1) {
try {
} catch (IOException e1) {
Can anybody tell me a possible solution??
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
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.
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?
I agree. Here's the link:
subject: opening serverSocket From servlet
It's not a secret anymore!