2 Replies - 2549 Views - Last Post: 29 September 2013 - 06:53 PM Rate Topic: -----

#1 funkyt711   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 12-September 13

Client/Server Socket Program inexplicably hangs

Posted 28 September 2013 - 10:35 PM

I have a fairly simple client/server program which uses a socket to communicate locally between the Client GUI and the Server GUI. I have the functionality working fine. The server connects to the client and from the client window you specify a file path to open. The Server then retrieves the text file from the system and parses the data and sends it through to the client. So far the client gets the first two lines of data and then just hangs with no errors or anything in eclipse. I am completely lost since there is nothing to warn me about.

Client class
public class Client extends JFrame implements ActionListener
{
   /**
	 * 
	 */
   private static final long serialVersionUID = 1L;
   private JTextField enterField; // text field to accept in from user
   private JTextArea displayArea; // display area to display information from user
   private BufferedReader in; // in from user
   private PrintWriter out; // out to server
   private Socket connection; // connection to server
   private JPanel contentPane; // panel to hold components

   // set up GUI, connect to server, and get streams
   public Client()
   {
	   	setTitle("TCP Client");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		Label label = new Label("Enter filename to retrieve:");
		label.setAlignment(Label.CENTER);
		label.setBounds(10, 10, 154, 22);
		contentPane.add(label);
		
		enterField = new JTextField();
		enterField.setBounds(170, 10, 254, 22);
		contentPane.add(enterField);
		enterField.addActionListener(this);
		
		JScrollPane scroller = new JScrollPane();
		scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scroller.setBounds(10, 38, 414, 213);
		contentPane.add(scroller);
		
		displayArea = new JTextArea();
		displayArea.setEditable(false);
		scroller.setViewportView(displayArea);
		setVisible(true); // show window
	   
	 /*  
	 setTitle("TCP Client");
	 label = new JLabel ( " Enter the FILE NAME to retrieve: ");
     panel = new JPanel(); // create panel
     panel.setLayout ( new GridLayout (1, 2, 0, 0));
     panel.add( label ); // add label to panel
     enterField = new JTextField(); // create text field
     enterField.addActionListener( this ); // add action listener
     panel.add( enterField ); // add text area to panel
     displayArea = new JTextArea(); // add text area
     displayArea.setEditable(false);
     scroller = new JScrollPane( displayArea ); // add scrolling
     //scroller.setHorizontalScrollBarPolicy(0);
     setLayout( new BorderLayout() ); // set layout of JFrame
     add( panel, BorderLayout.NORTH); // add panel  to north
     add( scroller, BorderLayout.CENTER); // add scrolling text area to center
		*/
		
		
     try // connect to server, get streams
     {
         // create socket to make connection to server
    	 // local host address and port identical to server port number
         connection = new Socket(InetAddress.getLocalHost(), 7985);
         
         /*
          * Get I/O Streams
          * Generate new buffered writer & reader
          */
         out = new PrintWriter(connection.getOutputStream(), true); // out stream to server
         
         in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // in stream from server
     } // end try
     catch( IOException ioexception)
     {
         ioexception.printStackTrace();
     } // end catch
 
   } // end client constructor


   // process file name entered by client
   public void actionPerformed(ActionEvent event)
    {
       try      // display contents of file
       {
           String fileName  = event.getActionCommand() + "\n";
           out.format(fileName); // put file name in stream
           
           String inFromServer = in.readLine(); // read response from server
           
           displayArea.setText(inFromServer);
           
           if(inFromServer.equals("The contents of the file you requested:")){
           	   displayArea.append(inFromServer);
           	   
        	   while (inFromServer != null); // read new line
               {
            	   displayArea.append(inFromServer); // add line to text area  
            	   inFromServer = in.readLine(); // read response from server 
               } // end while
           }
           
           enterField.setEditable(false);
           
           out.close();      // close out
    	   in.close();       // close in
    	   connection.close();  // close connection
    	   
       } // end try
       catch ( EOFException eofException ) {
    	   
       }
       catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
       }

       } // end finally
    } // end Client class



Server class
public class Server extends JFrame
{
	private static final long serialVersionUID = 1L;
	private PrintWriter out; // out stream to client
	private BufferedReader in; // in stream from client
    private ServerSocket server; // server socket
    private Socket connection; // connection to client
    private JPanel contentPane;
    private JTextArea outputArea;

   // set up GUI
   public Server()
   {
	    setTitle("TCP Server");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		outputArea = new JTextArea();
		outputArea.setEditable(false);
		outputArea.setBounds(10, 11, 414, 240);
		contentPane.add(outputArea);
	    
       try
       {
            server = new ServerSocket( 7985, 10 ); // create ServerSocket
            // first parameter is port
            // second is how many clients server can queue
       } // end try
       catch (IOException exception)
       {
            exception.printStackTrace();
            System.exit(0);
       } // end catch


   } // end Server constructor

   // set up and run server
   public void runServer(int numConnection)
   {
      try // set up server to receive connections; process connections
      {
         //Connect to the server
    	 connectToServer(numConnection);
         
         //Setup streams
    	 setupStreams();
         
    	 
    	 // get file name from client
         File inputFile = new File(in.readLine());
         
         // result variable for
         String result;

         if (inputFile.isFile())
         {
             BufferedReader fileInput = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
             out.format("The contents of the file you requested:");
             
             result = fileInput.readLine();
             
             while (result != null)   // while there are more lines in the file
             {
            	 out.format(result + "\n");
            	 outputArea.append("SERVER>>> " + result + "\n");
            	 result = fileInput.readLine();
             } // end while
             
             outputArea.append("\n");
             
         } // end if
         else
         { 
        	 result = "File not found. Be sure to enter full file path.";
             out.format(result + "\n");
             outputArea.append("SERVER>>> File not found on server.\n\n");
         } // end else
      } // end try
      catch (IOException ioException)
      {
         ioException.printStackTrace();
         System.exit(0);
      } //  end catch
      finally
      {
          try
          {
              //out.close();       // close out
              //in.close();        // close in
              connection.close();   //close connection
              
              outputArea.append("Server Terminated connection.\n");
              outputArea.append("Terminating connection.\n\n");
          } // end try
          catch (IOException ioException)
          {
            ioException.printStackTrace();
            System.exit(0);
          } //  end catch
      } // end finally
    } // end runServer method
   
   private void connectToServer(int numConnection) {
	   outputArea.append("Waiting for connection...\n");
  	 
       try {
		connection = server.accept();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
  	 
  	 if( connection.isConnected()) {
  		 String ip = null;
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  		 outputArea.append("Connection " + numConnection + " received from: " + ip + "\n");
  	 }
   }
   
   private void setupStreams() {
	   try {
		out = new PrintWriter(connection.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	   outputArea.append("Got I/O Streams\n\n");
   }
}



My Main functions
public class ServerTest
{
   private static int numConnections = 1;
	
   public static void main( String[] args )
   {
      Server application = new Server(); // create server
      application.setVisible(true);
      
      while(true) {
    	  application.runServer(numConnections); // run server application
    	  numConnections++;
      }
   } // end main
} // end class ServerTest



public class ClientTest
{
   public static void main( String[] args )
   {
      Client application = new Client(); // create client application
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   } // end main
} // end class ClientTest



Is This A Good Question/Topic? 0
  • +

Replies To: Client/Server Socket Program inexplicably hangs

#2 natecat   User is offline

  • D.I.C Head

Reputation: 57
  • View blog
  • Posts: 233
  • Joined: 19-December 11

Re: Client/Server Socket Program inexplicably hangs

Posted 28 September 2013 - 11:48 PM

.readLine() (I think) will continue to wait until it receives data. I'm confused on why you don't just send the file as one big string.
Was This Post Helpful? 1
  • +
  • -

#3 funkyt711   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 12-September 13

Re: Client/Server Socket Program inexplicably hangs

Posted 29 September 2013 - 06:53 PM

View Postnatecat, on 28 September 2013 - 11:48 PM, said:

.readLine() (I think) will continue to wait until it receives data. I'm confused on why you don't just send the file as one big string.


Hey thanks alot for the insight. I totally didn't even think about just sending the file as one big string and then parsing the data at the other end. makes complete sense
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1