Solved

unreachable statement try { error

Posted on 2003-12-10
9
802 Views
Last Modified: 2008-03-03
hi,

im trying to 'mash' a server and client together, with not much success, the code looks as follows:

import java.net.*;
import java.io.*;


public class server2
{

      
static final int LISTENING_PORT = 4130;
   
   
      public static void main(String[] args) {
     
         File folder;        // The directory from which the
                                //    gets the files that it serves.
         ServerSocket listener; // Listens for connection requests.
         Socket connection;     // A socket for communicating with
                                //                a client.
         
        PrintWriter outgoing;
         
         TextReader incoming;  

         String command;       // Command to send to the server.
   
        //server element below
         
         
         /* Get the directory name from the command line, and make
            it into a file object.  Check that the file exists and
            is in fact a directory. */
      
         
                  
             folder = new File("stuff");

         if ( ! folder.exists() ) {
            System.out.println("Folder: " + folder +" -- does not exist.");
            return;
         }
         if (! folder.isDirectory() ) {
            System.out.println("The file you require is not a folder.");
            return;
         }
         
         /* Listen for connection requests from clients.  For
            each connection, create a separate Thread of type
            ConnectionHandler to process it.  The ConnectionHandler
            class is defined below.  The server runs until the
            program is terminated, for example by a CONTROL-C. */
               
         try {
            listener = new ServerSocket(LISTENING_PORT);
            System.out.println("\nServer listening on port " + LISTENING_PORT);
                  
            while (true) {
               connection = listener.accept();
               
            }
         }
         catch (Exception e) {
            System.out.println("Server shut down unexpectedly.");
            System.out.println("Error:  " + e);
            return;
            }
         
         //client element

         /* Make the connection and open streams for communication.
            Send the command to the server.  If something fails
            during this process, print an error message and end. */
         
         try {
            connection = new Socket( "localhost", LISTENING_PORT );
            incoming = new TextReader( connection.getInputStream() );
            outgoing = new PrintWriter( connection.getOutputStream() );
            outgoing.println(command);
            outgoing.flush();
         }
         catch (Exception e) {
            System.out.println(
                 "Can't make connection to server at localhost.");
            System.out.println("Error:  " + e);
            return;
         }
                  
             if (args.length == 0)
            command = "list";
         else
            command = "get " + args[0];      
         
         /* Read and process the server's response to the command. */
         
         try {
            if (args.length == 0) {
                  // The command was "filelist".  Read and display lines
                  // from the server until the end-of-stream is reached.
               System.out.println("File list from server:");
               while (incoming.eof() == false) {
                  String line = incoming.getln();
                  System.out.println("   " + line);
               }
            }
            else {
                  // The command was "get <file-name>".  Read the server's
                  // response message.  If the message is "ok", get the file.
               String message = incoming.getln();
               if (! message.equals("ok")) {
                  System.out.println("File not found on server.");
                  return;
               }
               PrintWriter fileOut;  // For writing the received data to a file.
               if (args.length == 2) {
                     // Use the third parameter as a file name.
                   fileOut = new PrintWriter( new FileWriter(args[1]) );
               }
               else {
                     // Use the second parameter as a file name,
                     // but don't replace an existing file.
                   File file = new File(args[0]);
                   if (file.exists()) {
                      System.out.println("A file with that name already exists.");
                      System.out.println("To replace it, use the three-argument");
                      System.out.println("version of the command.");
                      return;
                   }
                   fileOut = new PrintWriter( new FileWriter(args[1]) );
               }
               while (incoming.peek() != '\0') {
                      // Copy lines from incoming to the file until
                      // the end of the incoming stream is encountered.
                   String line = incoming.getln();
                   fileOut.println(line);
               }
               if (fileOut.checkError()) {
                  System.out.println("Some error occurred while writing the file.");
                  System.out.println("Output file might be empty or incomplete.");
               }
            }
         }
         catch (Exception e) {
            System.out.println("Sorry, an error occurred while reading data from the server.");
            System.out.println("Error: " + e);
         }
                  
      //new ConnectionHandler(folder,connection);      
      } // end main()

      //start connectionhandler here

   }//end server2 class

But im getting the following error, when i try to compile the file:

E:\server2.java:86: unreachable statement
         try {
         ^
1 error

Can anyone see where the code is going wrong? or what am i missing?

thanks
0
Comment
Question by:fimbria
  • 5
  • 3
9 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9913096
You need to make sure you have your return statements following a logical code progression. If your code must exit before a certain according to your return statements, it will report the above error.

0
 
LVL 15

Expert Comment

by:jimmack
ID: 9913160
The code enters a while(true) loop to sit and wait for connections.  The only way out of this is if an exception occurs.  In the catch, you return (exiting the main method), so nothing after that catch can ever be executed.

You probably can't do what you're trying to do without making some more serious changes.  eg. the server part needs to run in it's own thread.

Why are you "mashing" ;-) them together anyway?  The whole point of client/server is that you separate the two parts.
0
 

Author Comment

by:fimbria
ID: 9914834
So if i remove the "return" statement wil the code continue?
...or does the code further work than just removing and replacing the "return" command?

what do u mean by the "server" doing its own thread, would this be part of the "main"?

thanks
0
 
LVL 15

Accepted Solution

by:
jimmack earned 250 total points
ID: 9914943
>>  So if i remove the "return" statement wil the code continue?

No.  This is why I said that you need to make more serious changes.

I assume that previously this while loop (for the server to accept connections) was running in a separate VM (possibly, but not necessarily on another machine).  The while loop sits and waits forever for connections to be made from the client.  When a connection is made, at the moment it does nothing but start the loop again and wait for another connection.  The code after this (the client part) will never execute.

>> what do u mean by the "server" doing its own thread

I mean that you need another class that can run as a separate thread (ie. extends Thread or implements Runnable).  The while loop that waits for connections should go in there so that you can start this thread and get on with the client code.

Unless you have a really good reason for trying to get all this into a single application, I would strongly recommend keeping the server code and client code separate.

Regardless of whether you keep the code in one lump like this or split it out again, you'll need to add some code after the accept() line, otherwise nothing will happen when clients try to connect.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:fimbria
ID: 9916723
what sort of thing do you suggest after the "accept ()" line?

I would rather do the model as a separate server and client, just its for a uni project...so...my hands are tied.
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9916767
>> what sort of thing do you suggest after the "accept ()" line?

What should the server do?  Maybe read data from the client?  Create data and send it to the client?

What instructions have you been given for the project (in particular, what is the system supposed to do and what restrictions have been placed on you that prevents you from creating separate code for the server and client)?
0
 

Author Comment

by:fimbria
ID: 9916841
see specification below:

1.The most basic functionality is to provide a mechansim for transferring files between processes. If you think about it a file transfer is just a basic file copy program split into 2 halves - one side reads from a file and writes to a socket and the other side reads from a socket and writes to a file. You don't have to provide the functionality or mechanism of FTP!
Therefore you could start by writing a simple client that requests a file by name and a simple server that sends that file.

2.You want either side of the communication to be able to request the file or to have it requested. Therefore your next step is to put the server and the client together in one. You will then have a peer-to-peer transfer.
This is going to be a bit trickier because your server will have to be able to respond to either an incoming request on the server socket OR to a keyboard input specifying the file to fetch so that you can start a "client" to request it

3.The final stage is to modify the "client" part to implement a discovery to find out which server has the file before it can request it.


-------------------
At the moment i have done number 1... trying number 2 now
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9916982
If you've done 1. and you're happy that it is working OK, then you should already have the code that follows the accept().

Even within one application, you're going to need to separate out the server and client portions of the code.  It would probably be worthwhile having a word with your tutor.  At least that way you'll get guidance on what he expects rather than what we would suggest (there should be more marks in it that way ;-))
0
 
LVL 15

Expert Comment

by:jimmack
ID: 10248067
;-)
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

758 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