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 12 of 12

Thread: Second command to socket doesn't get through

  1. #1
    Junior Member
    Join Date
    Aug 2011
    Posts
    13
    My Mood
    Cool
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Second command to socket doesn't get through

    Hi there,

    My application works as a client/server architecture where I send commands to a server through sockets which are then initialized and executed to a Server class and finally a CPU class.
    The Server class initializes the CPU class and the CPU class initializes the CPU utilization.

    When i send the start commando the Server class creates a new thread for the CPU class which start the CPU utilization.
    This all works fine. My problem arises when I want to stop the thread by sending a stop command trough the socket. Is doesn't initialize.

    The process flows goes like this:
    1. Command send from JSP page to Client class
    2. Client class initializes a connection and send the command
    3. Command is interpreted bij JANEServer class and send to Server class
    4. Server class executes the start and stop method of the CPU class
    5. CPU class start the method for utilization.

    Below I posted the code and I hope someone is able to help me because I'm getting a little frustrated because I can't figure out what I'm doing wrong here.

    JANEServer class:
     
    import java.net.*;
    import java.io.*;
     
    /**
     * JANEServer class for creating the server sockets and
     * interpreting the commands send by the JANE client 
     * 
     * @author Sander Stad
     * @version 0.1
     * 
     */
    public class JANEServer {
     
    	private static Server iServer = null;				// Declaration of the JANEServer class
    	private static Socket socket = null;				// Declaration of the socket
    	private static ServerSocket socketServer = null;	// Declaration of the server socket
     
    	private static final int PORT = 20000;				// Constant variable for default port
     
    	/**
    	 * Constructor of the JANEServer class with default settings
    	 */
    	public JANEServer(){}
     
    	private void startServer(){
    		try {
    			// Open a socket with the default port
    			socketServer = new ServerSocket(PORT);
    		} catch (IOException e) {
    			// Print error if port could not be bound
    			System.out.println("Could not listen on port: " + PORT);
    			// Exit system
    			System.exit(1); 
    		}
    		// Server is ready for connections. Print status
    		System.out.println("Waiting for connection..");
     
    		try { 
    			// Accept connections
    			socket = socketServer.accept(); 
    		} 
    		catch (IOException e) 
    		{ 
    			// Print error if no connections can be accepted
    			System.err.println("Accept failed."); 
    			// Exit system
    			System.exit(1); 
    		}
     
    		// Connection is made with the client. Ready for commands
    		System.out.println ("Connection successful");
    		System.out.println ("Waiting for input.....");
    	}
     
     
    	private void startServer(int p){
    		try {
    			// Open a socket with port variable
    			socketServer = new ServerSocket(p);
    		} catch (IOException e) {
    			// Print error if port could not be bound
    			System.out.println("Could not listen on port: " + p);
    			// Exit system
    			System.exit(1); 
    		}
     
    		// Server is ready for connections. Print status
    		System.out.println("Waiting for connection..");
     
    		try { 
    			// Accept connections
    			socket = socketServer.accept(); 
    		} 
    		catch (IOException e) 
    		{ 
    			// Print error if no connections can be accepted
    			System.err.println("Accept failed."); 
    			// Exit system
    			System.exit(1);  
    		}
     
    		// Connection is made with the client. Ready for commands
    		System.out.println ("Connection successful");
    		System.out.println ("Waiting for input.....");
    	}
     
    	private void closeServer() throws IOException{
    		// Clean up sockets and readers
    		socket.close(); 
    		socketServer.close();
    	}
     
    	/**
    	 * Main method for executing the JANEServer class
    	 * @param args
    	 * @throws IOException
    	 */
     
    	public static void main(String args[]) throws IOException{
     
    		JANEServer jServer = new JANEServer();
    		jServer.startServer(PORT);
     
    		// Initialize Server class for performance issues
    		iServer = new Server();
     
    		// Create print writer to enable outputs
    		PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    		// Create buffered reader to read commands send from the client
    		BufferedReader in = new BufferedReader( 
    				new InputStreamReader( socket.getInputStream())); 
     
    		// Input line for getting commands from buffered reader
    		String inputLine; 
     
    		// Loop the buffered reader until it is null
    		while ((inputLine = in.readLine()) != null) 
    		{ 
    			// Print commands send by connected client
    			System.out.println ("Server: " + inputLine); 
    			out.println(inputLine); 
     
    			if(inputLine.equals("startcpu")){ iServer.startCPU(); }
    			if(inputLine.equals("stopcpu")){ iServer.stopCPU(); } 
    			if(inputLine.equals("disconnect")){ 
    				jServer.closeServer();
    				out.close(); 
    				in.close(); 
    				break;
    			}
    		} 
    	}
     
     
    }

    Server class:
     
    /**
     * Server class for executing commands to performance issue
     * classes i.e. the CPU
     * 
     * @author Sander
     * @version 0.1
     */
    public class Server {
     
    	private volatile CPU cpu;
    	private Thread threadCPU; 
     
    	/**
    	 * Standard constructor for the Server class
    	 */
    	public Server(){
    		cpu = new CPU();
    		threadCPU = new Thread(cpu, "CPU");
    	}
     
    	/**
    	 * Starts a CPU thread which causes CPU utilization
    	 */
    	public void startCPU(){
    		// Check if no other thread is already started
    		if(!cpu.isRunning()){
    			// Start the thread
    			threadCPU.start();
    			// Print status to screen
    			System.out.println("CPU Thread started!");
    		}else{
    			// If the thread is already alive print error to screen
    			System.out.println("CPU Thread is already alive!");
    		}
    	}
     
    	/**
    	 * Starts a CPU thread which causes CPU utilization with time limit
    	 * Stops the cpu automatically after x seconds
    	 * 
    	 * @param seconds	Amount of time in milliseconds until the thread stops
    	 */
    	public void startCPU(int seconds){
    		try {
    			// Check if no other thread is already started
    			if(!cpu.isRunning()){
    				// Start the thread
    				threadCPU.start();
    				// Print status to screen
    				System.out.println("CPU Thread started!");
    			}else{
    				// If the thread is already alive print error to screen
    				System.out.println("CPU Thread is already alive!");
    			}
    			// Sleep for x seconds
    			Thread.sleep(seconds);
    			stopCPU();
    		} catch (InterruptedException e) {
    			// Print the stack trace when exception occurred
    			e.printStackTrace();
    		}
    	}
     
    	/**
    	 * Stops a CPU thread
    	 */
    	public void stopCPU(){
    		// Request a stop in the CPU class
    		System.out.println("Stop initiated");
    		cpu.requestStop();
    		threadCPU.interrupt();
    		// Check if the thread successfully stopped
    		if(!cpu.isRunning()){
    			// Print status to screen
    			System.out.println("CPU Thread is stopped");
    		}
     
    	} 
     
     
    }

    CPU class:
    /**
     * CPU class for creating CPU utilization
     * 
     * @author Sander
     * @version 0.1
     */
    public class CPU implements Runnable{
    	// Initialize variables
    	@SuppressWarnings("unused")
    	private long value = 10L;
    	private volatile boolean running = false;
     
    	/**
    	 * Standard run method for the Runnable interface
    	 */
    	public void run() {
    		// Set running variable to true
    		this.running = true;
    		// Loop al long as the running variable is true
    		while(running){
    			// Increase variable that causes CPU utilization
    			this.value += 1L;
    		}
    	}
     
    	/**
    	 * Stops the while loop which causes the CPU utilization
    	 */
    	public void requestStop(){
    		if(running){
    			// Set running variable to false
    			running = false;
    		}else{
    			System.out.println("CPU isn't running!");
    		}
    	}
     
    	/**
    	 * Returns if the CPU utilization is running or not
    	 * @return boolean 
    	 */
    	public boolean isRunning(){
    		if(running){
    			// If CPU utilization is running return true
    			return true;
    		}
     
    		return false;
    	}
     
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Second command to socket doesn't get through

    What I'd do to find the problem is add lots of println statements to show the execution flow and to show the values of variables as they change. The print outs will help you understand what the code is doing so you can find where it is going wrong.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Second command to socket doesn't get through

    How can anyone test your code?

  4. #4
    Junior Member
    Join Date
    Aug 2011
    Posts
    13
    My Mood
    Cool
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Second command to socket doesn't get through

    I don't have a clue where the problem exists and I've tried several println statements.
    As soon as the first command to start the cpu utilization has started no other command can come through.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Second command to socket doesn't get through

    no other command can come through.
    That sounds like something is blocking.

    How can anyone test your code? Do you have a client and a testing script/program?

  6. #6
    Junior Member
    Join Date
    Aug 2011
    Posts
    13
    My Mood
    Cool
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Second command to socket doesn't get through

    I have a JSP page and clien class which interact with eachother.
    You can start the JANEServer class which creates a serversocket on port 20000 on the localhost.
    The JANEServer is included in the reply:
    JANEServer_20110826-2.zip

    If you have Tomcat installed you can use the war-file attached and execute JANEClient.jsp.
    The war-file is renamed to zip to be able to post in the reply. Just rename is to JANEClient.war

    JANEClient.zip

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Second command to socket doesn't get through

    Is a server necessary for testing? Can it be done with a local client class?

  8. #8
    Junior Member
    Join Date
    Aug 2011
    Posts
    13
    My Mood
    Cool
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Second command to socket doesn't get through

    It can be done with a simple workstation. That's where I do my testing on.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Second command to socket doesn't get through

    Why do you need a server to test this? I think there is a much simpler way to test the socket and I/O classes you are using.

    The zips you posted didn't have the source for the Client class.

  10. #10
    Junior Member
    Join Date
    Aug 2011
    Posts
    13
    My Mood
    Cool
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Second command to socket doesn't get through

    Here is the code for the Client class:
    import java.net.*;
    import java.io.*;
     
    import sun.nio.cs.ext.ISCII91;
     
    public class Client {
     
    	private static final String HOSTNAME = "127.0.0.1";
    	private static final int PORT = 20000;
     
    	private Socket socket;
    	private BufferedWriter wr;
     
    	public void connectServer(){
    		try {
    			socket = new Socket(HOSTNAME, PORT);
    		} catch (UnknownHostException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    	}
     
    	public void sendCommand(String c) throws InterruptedException{
    		connectServer();
    		if(getConnectionStatus()){
    			if(c.equals("disconnect")){
    				disconnectServer();
    			}else{
    				try{
    					wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    					wr.write(c);
    					wr.flush();
    					wr.close();
     
    				}catch(IOException iex){
     
    				}
    			}
    		}
    		disconnectServer();
    	}
     
    	public boolean getConnectionStatus(){
    		return socket.isConnected();
    	}
     
    	public void disconnectServer(){
    		if(socket != null){
    			try {
    				socket.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
     
    	}
    }

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Second command to socket doesn't get through

    I think your problem is an inconsistency between the sending of the message and the reading of the message:
    This reads the message. Read the API doc for what this method does:
    while ((inputLine = in.readLine()) != null)

    What does the String that is sent contain? Does it satisfy what the readLine wants?

    You have not posted the code that sends the String to show what is being sent.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Second command to socket doesn't get through

    Perhaps this will help. Here is my test script:
       public static void main(String args[]){
          Thread t = new Thread(new Runnable() {
             public void run() {
                new ClientServerProblem3();
             }
          });
          t.start();
     
          // Q&D client
          try {
             System.out.println("Client starting");
             Socket soc = new Socket("127.0.0.1", PORT);
             OutputStreamWriter output = new OutputStreamWriter(soc.getOutputStream() );
             output.write("startcpu\n");
             output.flush();
             Thread.sleep(500);
             output.write("stopcpu\n");
             output.flush();
             Thread.sleep(50);
             output.write("disconnect\n");
             output.flush();
             Thread.sleep(50);
             output.close();
             System.out.println("Client closed");
          }catch(Exception x){x.printStackTrace();}
       } // end main()
    Here is the program's print outs:
    Running: D:\Java\jdk1.6.0_25\jre\bin\java.exe -Xmx512M -classpath D:\JavaDevelopment;.;..\. ClientServerProblem3

    client starting
    Waiting for connection..
    2Connection successful
    2Waiting for input.....
    Server cons
    Server: startcpu< at 1314453930093
    CPU Thread started!
    CPU run started
    Server: stopcpu< at 1314453930593
    Stop initiated
    CPU Thread is stopped
    CPU run exiting value=129719427
    Server: disconnect< at 1314453930640
    Client closed

    0 error(s)

Similar Threads

  1. jre version in command line
    By major in forum What's Wrong With My Code?
    Replies: 2
    Last Post: June 14th, 2011, 06:55 AM
  2. Program.jar -command
    By luigi10011 in forum Java Theory & Questions
    Replies: 1
    Last Post: April 23rd, 2011, 09:49 AM
  3. [SOLVED] Send a F5 command
    By mds1256 in forum Object Oriented Programming
    Replies: 2
    Last Post: March 18th, 2011, 03:23 AM
  4. Run 2 systems command in applet, how?
    By bulgin in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 8th, 2010, 03:11 PM
  5. [SOLVED] Command Line Argument Help
    By EmSaint in forum Loops & Control Statements
    Replies: 2
    Last Post: January 28th, 2010, 10:55 AM