2016-12-18 14 views
0

我应该写一个程序,它将一些.class文件作为服务,并且它们应该被加载并执行服务。我已经使用套接字编程完成了它,但是因为我已经使它成为多线程的,所以服务可以被任意数量的客户端使用,我得到了在每个客户端线程完成后发生在无限while循环中的套接字关闭异常。即使有一个客户我仍然得到这个例外。我没有得到异常的唯一时间是当没有课程加载我使用中断。我试图找到问题并搜索了很多,但我找不到任何东西。 //这是服务器端套接字关闭异常发生在一个无限循环中

package reg.main; 
    import java.net.*; 
    import java.io.*; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
    import java.util.*; 
    import java.util.concurrent.*; 

    public class Application{ 
     private final static Logger LOGGER = LoggerFactory.getLogger(Application.class); 

     public static void main(String[] args){ 
      while(true){ 
       InputStream input = null; 
       Properties prop = new Properties(); 

       try{ 
       String filename = "config.properties"; 
       input = Application.class.getClassLoader().getResourceAsStream(filename); 
       if(input == null){ 
        System.out.println("Sorry, unable to find " + filename); 
       } 
       prop.load(input); 
       } 
       catch(IOException ex){ 
        System.out.println("properties file does not exist."); 
       } 
       try{ 
        String port = prop.getProperty("port"); 
        int portNo = Integer.parseInt(port); 
        ServerSocket serverSocket = new ServerSocket(portNo); 
        LOGGER.debug("Server is listening... on port " + portNo); 

        ExecutorService service = Executors.newFixedThreadPool(1); 
        service.execute(new Server(serverSocket.accept())); 

        serverSocket.close(); 
        service.shutdown(); 

       }catch (IOException e) { 
        System.out.println("Could not close socket"); 
        System.exit(1); 
       } 

      } 

     } 

    } 

// this is server side code 

    package reg.main; 
    import java.net.*; 
    import java.io.*; 
    import reg.entity.*; 
    import reg.utility.*; 
    import reg.service.*; 
    import reg.dao.*; 
    import java.util.*; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 

    public class Server implements Runnable{ 
     private static final Logger LOGGER = LoggerFactory.getLogger(Server.class); 
     private Socket clientSocket; 

     public Server(Socket clientSocket){ 
      LOGGER.debug("Connection is Established."); 
      this.clientSocket = clientSocket; 
     } 

     public void run(){ 
      ObjectOutputStream outToClient = null; 
      ObjectInputStream inFromClient = null; 

      try{ 
       outToClient = new ObjectOutputStream(clientSocket.getOutputStream()); 
       inFromClient = new ObjectInputStream(clientSocket.getInputStream()); 
      } 
      catch(IOException ex){ 
       LOGGER.error("There is a problem in reading or writing."); 
      } 
      while(true){ 
       try{ 
        String userOption =(String)inFromClient.readObject();//while printing stack trace, it says there is something wrong with this line. i don't know why! 
        System.out.println(userOption); 
        userOption = DataEditor.editOptionInputInfo(userOption); //this is a custom method 
        Map<String,Service> mapper= CustomClassLoader.loadClass(); //in class loader .class files will be loaded and an object of each of them will be sent in a map 
        if(mapper == null){ 
         LOGGER.debug("no class file found to be loaded."); 
         clientSocket.close(); 
         break; 
        } 

        List<String> classNames = CustomClassLoader.getClassNames(); 
        boolean ckeckedUserOption = Validation.validUserOption(classNames,userOption); 

         if(ckeckedUserOption == false){ 
          LOGGER.error("client has entered the wrong option."); 
         } 

         System.out.println(userOption + "in server class------------- before loading class"); 
         Service service = mapper.get(userOption); 
         List<String> parameters = service.getRequiredParameters(); 
         if(parameters.size() == 0){ 
          LOGGER.debug("There is a problem with loaded classes."); 
         } 

         outToClient.writeObject(parameters); 
         LOGGER.debug("required parameters was sent to client."); 
         List<String>info = (List<String>)inFromClient.readObject(); 
         LOGGER.debug("Information from client has been sent."); 

         if(info.size() == 0){ 
          LOGGER.error("client has not put information. Try again."); 
          System.exit(2); 
         } 

         String result = service.doOperation(info); 
         outToClient.writeObject(result); 
         LOGGER.debug("Result of required service was sent to client."); 

         inFromClient.close(); 
         outToClient.close(); 
         //clientSocket.close(); 

       }catch(IOException ex){ 
        LOGGER.error("Exception caught when trying to listen on port " 
         + " or listening for a connection"); 
         ex.printStackTrace(); 
       } 
       catch(ClassNotFoundException ex){ 
        LOGGER.error("class was not found."); 
       } 
      } 
     } 
    } 
// this is client side 

package reg.main; 
import java.net.*; 
import java.io.*; 
import java.util.*; 
import java.util.Scanner; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

//Client class 

    public class Client{ 
     private final static Logger LOGGER = LoggerFactory.getLogger(Client.class); 

     public static void main(String[] args){ 


      Socket clientSocket = null; 
      String userOption; 

      InputStream inputStream = null; 
      Properties prop = new Properties(); 

      try{ 
       String filename = "config.properties"; 
       inputStream = Client.class.getClassLoader().getResourceAsStream(filename); 
       if(inputStream == null){ 
        System.out.println("Sorry, unable to find " + filename); 
       } 
       prop.load(inputStream); 
       } 
       catch(IOException ex){ 
        System.out.println("properties file does not exist."); 
       } 
      try{ 
       Scanner input = new Scanner(System.in); 
       System.out.println("Do you want to sign in or login? put the file name in:"); 
       String path = input.next(); 
       LOGGER.debug("User entered " + path + " as the service option."); 
       String port = prop.getProperty("port"); 
       int portNo = Integer.parseInt(port); 
       FileReader fileReader = new FileReader(path); 
       BufferedReader reader = new BufferedReader(fileReader); 
       userOption = reader.readLine(); 

       clientSocket = new Socket("192.168.121.114", portNo); 
       System.out.println("client is connected to the server."); 

       ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream()); 
       ObjectInputStream inFromServer = new ObjectInputStream(clientSocket.getInputStream()); 

       outToServer.writeObject(userOption); 
       LOGGER.debug("sent the user option to server ==> " + userOption); 

       List<String> listOfparams =(List<String>)inFromServer.readObject(); 
       LOGGER.debug("List of Requierements in Client " + listOfparams); 
       List<String> info = new ArrayList<String>(); 
       for(String param : listOfparams){ 
        System.out.println("Enter your " + param + ": "); 
        info.add(input.next()); 
       } 
       outToServer.writeObject(info); 
       String result = (String)inFromServer.readObject(); 
       LOGGER.debug("The result of required service: " + result); 
       System.out.println(clientSocket.isClosed()); 

       inFromServer.close(); 
       outToServer.close(); 
       clientSocket.close(); 

      } catch (UnknownHostException e) { 
       LOGGER.error("Don't know about host "); 
       System.exit(1); 
      } catch (IOException e){ 
       LOGGER.error("Couldn't get I/O for the connection to the host or there is no service for loading"); 
       System.exit(1); 
      } 
       catch(ClassNotFoundException ex){ 
       LOGGER.error("class does not found."); 
      } 
     } 
    } 

我感谢所有帮助主类。感谢ü提前

回答

0

使用break渔获

  try{ 
       String filename = "config.properties"; 
       input = Application.class.getClassLoader().getResourceAsStream(filename); 
       if(input == null){ 
        System.out.println("Sorry, unable to find " + filename); 
       } 
       prop.load(input); 
      } 
      catch(IOException ex){ 
       System.out.println("properties file does not exist."); 
       break; // this make program to go out of the loop 
      } 
+0

我很欣赏你的答案,但打破刚刚停止的循环,它并没有解决异常... – maryam

相关问题