Link to home
Start Free TrialLog in
Avatar of bored_shiva
bored_shiva

asked on

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

ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bored_shiva
bored_shiva

ASKER

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.
No problem.  You are most welcome!