java.net.SocketException: socket closed, What's going on?

I have the class below. When I try to use it, I get the following message:
java.net.SocketException: socket closed
      at java.net.PlainSocketImpl.socketAccept(Native Method)
      at java.net.PlainSocketImpl.accept(Unknown Source)
      at java.net.ServerSocket.implAccept(Unknown Source)
      at java.net.ServerSocket.accept(Unknown Source)
      at dimes.util.ServicesServer$ServicesServerThread.run(ServicesServer.java:193)

Notice that this class use to be called a different name (DisplayServer) and was used to update a GUI component. It is now being used for the same functions but without the GUI. (Hence all the commented-out stuff)

The best I can tell, the invocation looks like this:
            try {
                  lockSocket = new ServicesServer(33333);
            } catch (BindException e) {
                   logger.warning("Another instance is already running...");
                   return false;
                        }
                    return true;


A sort of interesting side effect of this invocation is that because I get a socketException, not a BindException, the program continues to run (invocation returns true) so I can see that the rest of it works, just this part seems to explode.

As you can see, this is part of a util package, this is the list of files in that package:
DipslayServer.java      <------old version, currently ignored by project
DirectorySearch.java   <------Unused, ignored by project
Announcer.java
CommUtils.java
DelayedTimerTask.java
FileHandlerBean.java
FileNameComparator.java
HeaderProducer.java
JarExtractor.java
LibraryLoader.java
Listener.java
Lock.java
MyEnum.java
ResourceManager.java
ServicesServer.java
StreamGobbler.java
TimeSlot.java

Any help would be greatly appreciated. If you need any more of the classes surrounding this, please ask.  This project has a few hundred classes, and I didn't want to start recursively posting all of them. ;>
Thanks in advance.

/*
 * Created on 27/03/2005
 *
 */
package dimes.util;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
 
import dimes.Agent;
import dimes.measurements.Measurements;
import dimes.util.logging.Loggers;
 
/**
 * a class acting as a server to graph state requests
 * 
 * note that:
 * 1. currently, this 'server' is meant to server only one
 * 		client - security reasons. also - this client must be
 * 		al localhost.
 * 
 * 2.  the server holds a listening thread  - so in order to 
 * 		start the server one must use startServer() and in order to exit
 * 		smoothly one must  use stopServer()
 * 
 * ****************************************************************
 * Added in version 0.5.0: In case of IOException in the thread the run() method will be terminated - to avoid endless loop.
 */
public class ServicesServer extends ServerSocket
{
 
	// members :
	private ServicesServerThread listener;
	private Agent agent;
	Socket servicesClientSocket = null;
	private ObjectOutputStream out = null;
 
	/************
	 * constructor 
	 * TODO : don't take an agent , but a class implementing
	 * some interfae with getCurrentGraphStateRecord().
	 * 
	 * @param port
	 * @param myAgent
	 * @throws IOException
	 */
	public ServicesServer(int port) throws IOException
	{
		super(port);
		boolean a =this.isBound();
		boolean b = this.isClosed();
		boolean c=true;
	}
 
	public void setAgent(Agent myAgent)
	{
		agent = myAgent;
	}
 
	/***************
	 * this function must be used in order to smoothly close 
	 * the server
	 *
	 */
	public void stopServer()
	{
		listener.stopServer();
	}
 
	public void startServer()
	{
		Loggers.getLogger().fine("Started Display server.");
		listener = new ServicesServerThread(this);
		listener.start();
	}
 
	/**
	 * @param requestSocket
	 * @throws IOException
	 */
/*	private void handleRequest(Socket clientSocket) throws IOException
	{
 
		servicesClientSocket = clientSocket;
		out = new ObjectOutputStream(servicesClientSocket.getOutputStream());
		BufferedReader in = new BufferedReader(new InputStreamReader(servicesClientSocket.getInputStream()));
		String inputLine, outputLine;
 
		try
		{
			while ((inputLine = in.readLine()) != null)
			{
				//                    System.out
				//                            .println("<------------------ read : --------------->");
				//                    System.out.println(inputLine);
				if (inputLine.equals("DisplayIPs"))
				{
					Loggers.getLogger().fine(outputLine);
					outputLine = getCurrectGraphStateRecord();
					out.writeObject(outputLine);
					out.flush();
				}
			}
		}
		catch (Exception e)
		{
 
		}
 
		out.close();
		in.close();
		clientSocket.close();
		this.removeClient();
	}*/
 
	/**
	 * remove the one and only client.
	 * 
	 */
	private void removeClient()
	{
		Loggers.getLogger().fine("Removing ScreenSaver client.");
		servicesClientSocket = null;
		out = null;
	}
 
	/**
	 * @return the current edges of the graph as xml
	 */
/*	private String getCurrectGraphStateRecord()
	{
		return agent.getCurrectGraphStateRecord();
	}*/
 
	/**
	 * publish a string message to the client.
	 * 
	 * @param msg
	 */
	public void publish(String msg)
	{
		if (servicesClientSocket == null || out == null)
		{
			//            System.out.println("No live TCP client was found.");
			return;
		}
		//        System.out.println("Publishnig to a live client :\n" + msg);
		try
		{
			out.writeObject(msg);
			out.flush();
		}
		catch (Exception e)
		{
			removeClient();
		}
 
	}
 
	/**********************
	 *  a listener thread class for the server.
	 * 
	 * @author Ohad Serfaty
	 *
	 */
	class ServicesServerThread extends Thread
	{
 
		ServicesServer server;
		private boolean stopServer = false;
 
		ServicesServerThread(ServicesServer theServer)
		{
			server = theServer;
		}
 
		public void run()
		{
 
			while (!stopServer)
			{
				Socket requestSocket = null;
				try
				{
					requestSocket = server.accept();
					InetAddress remoteAddress = requestSocket.getInetAddress();
					System.out.println("address: " + remoteAddress.getHostAddress());
 
					// Security check :
					//                    if (! (remoteAddress.getHostAddress().startsWith("127.0.0") ||
					//                            (remoteAddress.getHostAddress().startsWith("192.168") ||
					//                            InetAddress.getLocalHost().equals(remoteAddress)) ))
					if (!(Measurements.isPrivateIP(remoteAddress.getHostAddress()) || InetAddress.getLocalHost().equals(remoteAddress)))
						throw new IOException("Attempt to connect out of localhost blocked.");
					Loggers.getLogger().info("Connected with screen saver from address:" + remoteAddress);
//					if (requestSocket != null)
//						server.handleRequest(requestSocket);
				}
				catch (IOException e)
				{
					Loggers.getLogger().severe("Services Server stopped.");
					Loggers.getLogger().severe("Problem with Services Server Socket.");
					e.printStackTrace();
					server.removeClient();
					stopServer = true;
					stopServer();
				}
			}
			/*System.out.println*/Loggers.getLogger(this.getClass()).finest("Display thread stopped");//debug
		}
 
		/****************
		 * stop the server : indicate the thread to stop 
		 * and the server to close.
		 *
		 */
		public void stopServer()
		{
			/*System.out.println*/Loggers.getLogger(this.getClass()).finest("stopping server");
			stopServer = true;
			try
			{
				server.close();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
 
	}
 
}

Open in new window

bored_shivaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kevin CrossChief Technology OfficerCommented:
at dimes.util.ServicesServer$ServicesServerThread.run(ServicesServer.java:193)
The line numbers in code are not matching up, but can at least see you are in the run method which has a try/catch block; however, you are catching on IOException only.  There is not a problem with this if that is how your application needs to function; however, for debugging lets do this if you can:
Add an extra catch block:
catch(java.net.SocketException se) {
   //  log details of se -- try stack trace, message, inner exception/cause
}
Alternatively, change IOException to be Exception temporarily and we can ensure that all errors will stop the server and give you log trace.  Then you can see if we get any more details as the exact issue going on.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
TrigunaCommented:
I think the problem is in the following statement.
>> requestSocket = server.accept();
server is coming from an external thread. Do you think you need this thread? If possible try to remove the thread and check. You might end up with the solution.
0
bored_shivaAuthor Commented:
I ended up using a combined method based on both of these suggestions. Turns out that because this was a GUI updater, and the GUI has been removed, this class is actually superfluous (detailed tracing let me see who's looking for it, looking at  the external threads let me see they're not doing anything useful)
Thanks to both of you.
0
Kevin CrossChief Technology OfficerCommented:
No problem.  You are most welcome!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.