Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Socket program that worked in the past no longer working, cannot open socket.

  1. #1
    Member
    Join Date
    May 2013
    Posts
    106
    My Mood
    Amused
    Thanks
    16
    Thanked 9 Times in 9 Posts

    Default Socket program that worked in the past no longer working, cannot open socket.

    I wrote this program back in May that makes use of networking. It's a smallish program that is comprised of 2 parts, a client and a server. The server just receives information from a single client. The client is just a form in which you input an address. If you open the client without opening the server first, it doesn't work. It just says "NO CONNECTION TO SERVER" when you try to add a record. Which is what it's supposed to do.

    Anyway, for some reason, every time I open the server program, I get a BindException. I have this handled by a try-catch block, so it throws an error message of my own design "PORT ALREADY IN USE. EXITING." then it exits.

    I arbitrarily chose port 10,000 to handle the transmission of data, and port 9,000 to handle task IDs (I had to use a separate socket so that the server would know what to do with the information it was given). I chose these because as far as I know they aren't reserved by any regular TCP/IP protocols. Also, this program worked fine 5 months ago. What's the deal? Here's the code for the server portion if you think you can find anything relevant in there.

     
    public class P_AddressServer 
    {
    	//Text area to log activity.
    	private JTextArea jtaServerLog = new JTextArea();
     
    	//Socket for listening for objects.
    	private Socket listeningSocket;
     
    	//Integer input stream from client to get task ID.
    	private DataInputStream getTaskID;
     
    	//Object input and ouput streams from and to client.
    	private ObjectInputStream inputFromClient;
    	private ObjectOutputStream outputToClient;
     
    	//Integer to store flags indicating what the client wants.
    	private int userTask;
     
    	//ID of current record.
    	private int currentRecord = 0;
     
    	//Linked list to store the address objects.
    	LinkedList<Address> mailingList = new LinkedList<Address>();
     
    	P_AddressServer()
    	{
    		//Make the JFrame.
    		makeWindow();
     
    		//Sockets for listening for addresses and the task ID numbers.
    		ServerSocket serverSocket = null;
    		ServerSocket serverTaskSocket = null;
     
    		try 
    		{
    			//Open socket to client.  Listen on port 10000
    			serverSocket = new ServerSocket(10000);		
    			//Open socket to listen for the task ID.
    			serverTaskSocket = new ServerSocket(9000);
     
    			//Wait for input.
    			while(true)
    			{
    				//Begin listening.
    				listeningSocket = serverSocket.accept();
    				Socket taskListeningSocket = serverTaskSocket.accept();
     
    				//Input stream for receiving the task's ID.
    				getTaskID = new DataInputStream(taskListeningSocket.getInputStream());
     
    				//Get the task ID.
    				userTask = getTaskID.readInt();
     
    				//Process server task based on user's task choice.
    				if(userTask == Address.ADD)
    					serverSideAdd();
    				else
    					serverSideSingleItem(userTask);
    			}
     
    		} 		
    		catch (BindException e)
    		{
    			JOptionPane.showMessageDialog(null, "PORT ALREADY IN USE.  EXITING.");
    			System.exit(0);
    		}
    		catch (IOException e) 
    		{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} 
    		finally
    		{
    			try 
    			{
    				serverSocket.close();
    				serverTaskSocket.close();
    			} 
    			catch (IOException e1) 
    			{
    				// TODO Auto-generated catch block
    				e1.printStackTrace();
    			}
    		}
    	}
     
    	//Method to construct the GUI frame.
    	private void makeWindow()
    	{
    		//Create main frame.
    		JFrame logWindow = new JFrame("Server activity log.");
     
    		//Lock out user editing of server log.
    		jtaServerLog.setEditable(false);
     
    		//Log date and time of startup.
    		jtaServerLog.append("SERVER STARTED AT: ");
    		jtaServerLog.append(new Date().toString());
     
    		//Add elements to JFrame.
    		logWindow.add(new JScrollPane(jtaServerLog));
     
    		//Set attributes of frame.
    		logWindow.setVisible(true);
    		logWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		logWindow.setSize(600,350);
     
    	}
     
    	//Method to add addresses to linked list and server log.
    	private void serverSideAdd() throws IOException
    	{
    		//Create input and output streams.
    		inputFromClient = new ObjectInputStream(listeningSocket.getInputStream());
     
    		try
    		{
    			//Current record is last item in list.
    			currentRecord = mailingList.size();
     
    			Address newAddress = (Address)inputFromClient.readObject();
     
    			//Identify if this is the first address, and set the flag if it is.
    			if(mailingList.isEmpty())
    				newAddress.isFirst = true;
     
     
    			//Log address information to the server.
    			addStuffToLog(newAddress.name);
    			addStuffToLog(newAddress.street);
    			addStuffToLog(newAddress.city);
    			addStuffToLog(newAddress.state);
    			addStuffToLog(newAddress.zip);
     
    			//Add address from client to the linked list.
    			mailingList.add(newAddress);
     
    			//Move pointer of the last item.
    			mailingList.get(currentRecord).isLast = true;
     
    			//Next to last item is no longer the last item.  
    			//Disregard if this is the first item (size = 1, currentRecord = 0).
    			if(mailingList.size() > 1)
    				mailingList.get(currentRecord - 1).isLast = false;
    		}
    		catch(ClassNotFoundException e)
    		{
    			JOptionPane.showMessageDialog(null, "ADDRESS CLASS NOT FOUND.  EXITING.");
    			System.exit(0);
    		}
    		finally
    		{
    			//Close the input stream from the client.  Reopen when needed next time.
    			inputFromClient.close();
    		}
     
    	}	//End of serverSideAdd method.
     
    	//Method to send single address from the list to the client.
    	private void serverSideSingleItem(int userTask) throws IOException
    	{		
    		//Open data stream to send record information to client.
    		outputToClient = new ObjectOutputStream(listeningSocket.getOutputStream());
     
    		switch(userTask)
    		{	
    		//Current record is the first record.
    		case Address.FIRST:		currentRecord = 0;
    								break;
    		//Current record is one more than the previous.
    		case Address.NEXT:		currentRecord++;
    								break;
    		//Current record is one less than the previous.
    		case Address.PREVIOUS:	currentRecord--;
    								break;
    		//Current record is one less than the size of the whole list
    		case Address.LAST:		currentRecord = mailingList.size() - 1;
    								break;
    		//Just quit if somehow an integer other than one of our 4 constants got in.
    		default:				System.exit(0);
    								break;
    		}
    		/*
    		Check current record.  If it was record 0 when user entered this method,
    		and user hit the Previous button, set it back to 0 by incrementing.
    		If it was the last record and user hit Next, set it to the ID of the last
    		by decrementing.  
    		Set the respective flags to indicate if they are the first or last.
    		In this way, hitting previous on the first record will show the first record
    		and hitting next on the last record will show the last record.
    		*/
    		if(currentRecord == -1)
    			currentRecord++;
    		if(currentRecord == mailingList.size())
    			currentRecord--;
     
    		//Send current record.
    		outputToClient.writeObject(mailingList.get(currentRecord));	
    	}
     
    	//Method to add strings to the server log.
    	private void addStuffToLog(String addThis)
    	{
    		jtaServerLog.append("\n" +addThis);
    	}
     
    	//Program entry point.  Simply creates new server object.
    	public static void main(String[] args)
    	{
    		new P_AddressServer();
    	}
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    How can the code be executed for testing so the problem is shown?

    What changed between the last time the program worked and when it stopped working?

    Also it would help if the full text of the error message was printed in the catch block by calling the printStackTrace() method.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    May 2013
    Posts
    106
    My Mood
    Amused
    Thanks
    16
    Thanked 9 Times in 9 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Ooof. Forgot I posted this, and been too busy to reply back. Sorry about that.

    Quote Originally Posted by Norm View Post
    How can the code be executed for testing so the problem is shown?
    You only need the server portion, which I've pasted above, to see the problem. There's an Address class defined in a separate file that you would need to run the program properly, I think, but not having that would cause it to fail in a different place further down the line. Here is the Address class anyway:

    import java.io.Serializable;
     
    public class Address implements Serializable
    {
    	//Version ID.
    	private static final long serialVersionUID = 1L;
     
    	//Flags to indicate if this is first or last.
    	protected boolean isFirst;
    	protected boolean isLast;
     
    	//Integer flags for common tasks.  Shared between client and server.
    	protected static final int ADD = 100;
    	protected static final int FIRST = 200;
    	protected static final int NEXT = 300;
    	protected static final int PREVIOUS = 400;
    	protected static final int LAST = 500;
     
    	//Fields for address data.
    	protected String name;
    	protected String street;
    	protected String city;
    	protected String state;
    	protected String zip;
     
     
     
    	Address(String thisName, String thisStreet, String thisCity, String thisState, String thisZip)
    	{
    		this.name = thisName;
    		this.street = thisStreet;
    		this.city = thisCity;
    		this.state = thisState;
    		this.zip = thisZip;
    	}
    }

    What changed between the last time the program worked and when it stopped working?
    That's the perplexing thing. I haven't touched this code since then. I have an exported JAR file that I exported back in May. It still works.

    What else can I think of that's changed? I installed XAMPP on this computer so I could do PHP development. I moved the location of the Dropbox folder in which the program is stored on both my laptop and desktop.

    Maybe I need to do a new JAR file export and try running the new JAR on a couple other computers.

    Also it would help if the full text of the error message was printed in the catch block by calling the printStackTrace() method.
    Here's what I got:

    java.net.BindException: Address already in use: JVM_Bind
    at java.net.TwoStacksPlainSocketImpl.socketBind(Nativ e Method)
    at java.net.TwoStacksPlainSocketImpl.socketBind(Unkno wn Source)
    at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
    at java.net.TwoStacksPlainSocketImpl.bind(Unknown Source)
    at java.net.PlainSocketImpl.bind(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at P_AddressServer.<init>(P_AddressServer.java:62)
    at P_AddressServer.main(P_AddressServer.java:236)
    Here are lines 61 and 62 referenced in the stack trace.

    //Open socket to client.  Listen on port 10000
    serverSocket = new ServerSocket(10000);
    Last edited by mstabosz; October 18th, 2013 at 04:49 PM. Reason: Fixed an error with a quote tag.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    What ports do XAMPP use?
    Try opening your command prompt and entering: "netstat -a".
    It will list your ports. Have a look if the port in question is actually being used at the time.
    If it isn't being used and you are getting that exception, maybe some other condition is occurring to make that exception get thrown (perhaps a different exception "should" be thrown instead).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Member
    Join Date
    May 2013
    Posts
    106
    My Mood
    Amused
    Thanks
    16
    Thanked 9 Times in 9 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Quote Originally Posted by aussiemcgr View Post
    What ports do XAMPP use?
    Try opening your command prompt and entering: "netstat -a".
    It will list your ports. Have a look if the port in question is actually being used at the time.
    If it isn't being used and you are getting that exception, maybe some other condition is occurring to make that exception get thrown (perhaps a different exception "should" be thrown instead).
    XAMPP I think is only using 80 and 443. But I changed around to some other arbitrary port numbers and still got the same thing. Netstat doesn't show port 10,000 as being in use, so you're probably right... the port isn't actually in use. Some other condition is causing that BindException, and my error handling code just gave the misleading notion that the port was in use. Probably because when I coded it, I thought that a port being in use was the only thing that could cause a Bind Exception.

    The stack trace says "Address already in use." Could it be that the IP address (127.0.0.1) is getting hogged by XAMPP and that's what's causing the Bind Exception? But I get this same thing even when XAMPP isn't running. And the IP address shouldn't matter as long as you have an open TCP port, right? What else could cause the Bind Exception?

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Ok, so we need to do a bit of debugging.
    If the exported jar from May still works, and nothing has changed in the code, this could indicate some change in the java JDK, but it seems very unlikely that a JDK change would make this sort of impact.
    Does it work on other computers? Try the version from May and your current version on a different computer (if you can). If you get the same issue on another computer, we can probably rule out the computer as being the problem.
    You've already probably done this, but restart your computer and attempt to run the program before you've done anything else. If the port is in use, and it isn't after restarting, that would tell us that some other program may be doing something to the port.
    Have you tried a different port? Does this problem exist on every port you try? If so, this indicates the port is not the problem.
    Go to your Windows Task Manager, the Performance Tab, and press the Resource Monitor button. On the window that opens, go to the Network tab and expand the TCP Connections and Listening Ports sections. Keep an eye on those sections while debugging to see if anything interacts with the port you are trying to connect to.

    That's the best advice I can give right now.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. #7
    Member
    Join Date
    May 2013
    Posts
    106
    My Mood
    Amused
    Thanks
    16
    Thanked 9 Times in 9 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Hmmm...

    Earlier today tried the May export and the (newer) October export on a third computer and they both worked. Just now tried both on this computer, and they both worked. Then closed them and tried again, and neither work.


    ...wait... I think I missed this before. Netstat shows both ports 9000 and 10000 (the ports I arbitrarily chose) as being in use use in a "LISTENING" state. I'm a little fuzzy on how this stuff works. Will a port eventually reopen and become available again if it goes long enough without activity? Maybe it worked a few minutes ago because the port freed itself up after some time. Maybe this is happening because I didn't put anything in my code to close the sockets when the program closes. Or did I? I have two statements to close the sockets, but they're in a finally clause. I don't use finally that often--do they execute whether the "try" condition or the "catch" condition is executed? Would my finally clause be closing the socket whether it was opened successfully or not?

    Tell me if my thought processes are screwed up here.... I'm thinking...

    1) Program tries to open sockets (serverSocket = new ServerSocket(10000) and serverTaskSocket = new ServerSocket(9000))
    2) On success, program enters the infinite while loop and listens for object data on port 10000 and integers on port 9000.
    3) When user closes program, while loop terminates and the code in the finally clause executes.
    4) On failure, the code in the catch clause executes, which includes closing out the program via System.exit(0).... Does this termination stop the finally from executing?

    Yeah so it looks like ports 9000 and 10000 are still in use. Changed it over to 9001 and 10001 and the program works. So I guess I have a resource leak? How do I get those ports to free up when the program closes?

  8. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Ok, so clearly you are opening the port with your program and it is staying open. That is a good information for us to work with.
    The finally statement will almost always execute, even if an exception is thrown. In fact, I think the finally statement even executes if the program is exited during the try statement through conventional means. It is very reliable. HOWEVER, System.exit(int) is not a great idea to use if you can avoid it. It might stop the finally block from executing. If the exit() method throws a SecurityException, the finally statement will execute, but otherwise it usually won't. Ideally, a program should exit "naturally" every time (meaning it runs out of procedures to execute, instead of force exiting with System.exit()).
    Do you actually exit the while loop, or are you relying on it to just close on itself when the user exits? Because there is a time delay between when a java program "exits" and when the java VM finishes executing. If you exit a program in an infinite loop, the vm may still continue to run for a while (I've noticed like 2 or 3 minutes at most, which is a long time in computer terms).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #9
    Member
    Join Date
    May 2013
    Posts
    106
    My Mood
    Amused
    Thanks
    16
    Thanked 9 Times in 9 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Quote Originally Posted by aussiemcgr View Post
    Ok, so clearly you are opening the port with your program and it is staying open. That is a good information for us to work with.
    The finally statement will almost always execute, even if an exception is thrown. In fact, I think the finally statement even executes if the program is exited during the try statement through conventional means. It is very reliable. HOWEVER, System.exit(int) is not a great idea to use if you can avoid it. It might stop the finally block from executing. If the exit() method throws a SecurityException, the finally statement will execute, but otherwise it usually won't. Ideally, a program should exit "naturally" every time (meaning it runs out of procedures to execute, instead of force exiting with System.exit()).
    Hmm. Is there a better way? The System.exit(0) statement is inside that catch block. If it hits that, there are no other statements to execute, so it wouldn't do anything. But if I got rid of the exit statement, the window would stay open, and I don't want that.

    Do you actually exit the while loop, or are you relying on it to just close on itself when the user exits? Because there is a time delay between when a java program "exits" and when the java VM finishes executing. If you exit a program in an infinite loop, the vm may still continue to run for a while (I've noticed like 2 or 3 minutes at most, which is a long time in computer terms).
    No, there's no exit condition for the loop. I just rely on the user closing to terminate it. I can't think of a condition that would suffice. And it seems inappropriate to have an exit condition. The program is essentially emulating a server, and servers stay on until you shut them off. Also, stuffing the "listen for data" part inside an infinite loop is how I was taught to do it.

    Isn't there an event handler of some sort that can detect when a window is closed? I can't remember it off the top of my head, but I have used it recently. Maybe I could attach that to my window, and the action would be to close the sockets when the window is closed.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    The Window class has a WindowListener.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Look at what Norm advised. You can create a custom event for a window being closed. It would be a very good idea to handle closing the sockets in the window listener.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  12. #12
    Member
    Join Date
    May 2013
    Posts
    106
    My Mood
    Amused
    Thanks
    16
    Thanked 9 Times in 9 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Ok. Attaching a simple WindowListener got this all working correctly. I'm not crazy about the clutter caused by the 6 other methods the interface requires me to implement, but it is what it is. Thanks for helping me suss this out guys.

  13. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Socket program that worked in the past no longer working, cannot open socket.

    Most Listener interfaces also have abstract Adapters.
    Instead of having your custom window listener implement WindowListener, make it extend WindowAdapter (WindowAdapter (Java Platform SE 7 )) and only override the methods you need to.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. java Client Server program by using socket problem
    By Mad Engineer in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 31st, 2013, 10:57 AM
  2. previous tab's functions no longer working when new tab is created
    By captain in forum What's Wrong With My Code?
    Replies: 13
    Last Post: April 26th, 2012, 01:12 PM
  3. Cannot Open Socket on Specific Address/Port
    By dlamet in forum Java Networking
    Replies: 2
    Last Post: December 26th, 2011, 04:07 PM
  4. Socket not working well
    By tunai in forum Java Networking
    Replies: 4
    Last Post: October 7th, 2011, 07:39 AM
  5. Socket NIO connect not working under Solaris 10
    By trojanfoe in forum What's Wrong With My Code?
    Replies: 0
    Last Post: July 4th, 2011, 02:48 AM