Solved

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

Posted on 2008-11-02
4
9,578 Views
Last Modified: 2013-12-14
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

0
Comment
Question by:bored_shiva
  • 2
4 Comments
 
LVL 59

Accepted Solution

by:
Kevin Cross earned 250 total points
ID: 22862112
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
 
LVL 5

Assisted Solution

by:Triguna
Triguna earned 250 total points
ID: 22864621
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
 

Author Comment

by:bored_shiva
ID: 22865405
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
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 22866534
No problem.  You are most welcome!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

How to set-up an On Demand, IPSec, Site to SIte, VPN from a Draytek Vigor Router to a Cyberoam UTM Appliance. A concise guide to the settings required on both devices
As companies replace their old PBX phone systems with Unified IP Communications, many are finding out that legacy applications such as fax do not work well with VoIP. Fortunately, Cloud Faxing provides a cost-effective alternative that works over an…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Edureka is one of the fastest growing and most effective online learning sites.  We are here to help you succeed.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now