2012-05-01 11 views
0

임은 Java로 기본 전자 메일 시스템을 만들려고합니다. 나는 클라이언트가 연결하는 서버와 클라이언트를위한 GUI를 가지고있다. 서버가 클라이언트에서 새로운 연결을 선택하면 모든 다른 작업을 처리하는 새 스레드가 시작됩니다. 문제는 서버가 새 클라이언트를 승인하지만 실행중인 새 클라이언트 처리기 스레드를 시작하지 않는다는 것입니다. 어떤 도움이 필요합니까? 당신이 ObjectInputStream를 인스턴스화하는 경우 클라이언트가 충분한 헤더를 보낼 때까지클라이언트 처리기가 시작되지 않음

public class Server { 
    public static Connection link; 

    public static void main(String[] args) throws IOException { 
     ServerSocket serverSocket = null; 
     final int PORT = 1234; // Define the sockets and ports and i/o 
     Socket client; 
     ClientHandler handler; 

     try { 
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
     link = DriverManager.getConnection("jdbc:odbc:emails", "", ""); 
     System.out.println("Connected to Database . . . "); 
     } catch (ClassNotFoundException cnfEx) { 
     System.out.println("* Unable to load driver! *"); 
     System.exit(1); 
     } catch (SQLException sqlEx) { 
     System.out.println("* Cannot connect to database! *"); 
     System.exit(1); 
     } 

     try { 
     serverSocket = new ServerSocket(PORT); // Set the server socket 
     } catch (IOException ioEx) { 
     System.out.println("\nUnable to set up port!"); // If failed let the 
                 // user know 
     System.exit(1); // Exit the system with error code 1 
     } 

     System.out.println("\nServer running...\n"); // Tell the user the server 
                // is running 

     do { 
     client = serverSocket.accept(); 
     // Wait for client. 
     System.out.println(client); 
     handler = new ClientHandler(client); 
     System.out.println(handler); 
     System.out.println("\nNew client accepted.\n"); // Tell the user the 
                 // server has accepted 
                 // a client 
     System.out.println("RUNNING"); 
     handler.start(); // Start the handler 

     } while (true); // Continuous loop 
    } 

    static class ClientHandler extends Thread { 
     /** 
* 
*/ 
     private Socket client; 
     private ObjectInputStream input; // Define sockets, i/o and local array 
             // list 
     private ObjectOutputStream output; 

     public ClientHandler(Socket socket) throws IOException // Client handler 
                  // constructor 
     { 
     client = socket; 
     input = new ObjectInputStream(socket.getInputStream());// Set client 
                   // and i/o 
                   // stream 
     output = new ObjectOutputStream(socket.getOutputStream()); 
     } 

     public void run() { 
     String userCommand = null; 
     System.out.println("RUNNING CLIENT HANDLER"); 
     boolean quit = false; 

     do { 

      try { 
       userCommand = (String) input.readObject(); 
      } catch (IOException e2) { 
       // TODO Auto-generated catch block 
       e2.printStackTrace(); 
      } catch (ClassNotFoundException e2) { 
       // TODO Auto-generated catch block 
       e2.printStackTrace(); 
      } // Receive user command 

      if (userCommand.equals("SEND MESSAGE")) // If user command is to 
                // send a message 
      { 
       String username = null, recipient = null, message = null, insert, fileType = null; 

       try { 
        username = (String) input.readObject(); 
        recipient = (String) input.readObject(); // Receive username, 
                  // recipient and 
                  // message 
        message = (String) input.readObject(); 
        fileType = (String) input.readObject(); 
       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } catch (ClassNotFoundException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 

       insert = "INSERT INTO [emails] ([From], [To], [Message], [Attachment])" 
        + " VALUES('" 
        + username 
        + "','" 
        + recipient 
        + "','" 
        + message + "','" + fileType + "')"; 
       Statement statement = null; 
       try { 
        statement = link.createStatement(); 
        statement.executeUpdate(insert); 
        link.commit(); 
       } catch (SQLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       try { 

        getFile(input, fileType); 
       } catch (IOException ioEx) { 
        ioEx.printStackTrace(); 
       } catch (ClassNotFoundException cnfEx) { 
        cnfEx.printStackTrace(); 
       } 

       System.out.println(username // Tell the user a message has been 
              // sent 
        + " sent message to " + recipient); 
      } 

      if (userCommand.equals("READ MESSAGE")) // If user command is to 
                // read a message 
      { 
       String username = null; // Define local variables 

       try { 
        username = (String) input.readObject(); 
       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } catch (ClassNotFoundException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } // Receive the username of the current user 
       Statement statement = null; 
       String insert = "SELECT [Email No],[From],[Message],[Attachment] FROM [emails] WHERE To = '" 
        + username + "'"; 
       ResultSet rs = null; 
       try { 
        statement = link.createStatement(); 
        rs = statement.executeQuery(insert); 
       } catch (SQLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       try { 
        while (rs.next()) { 
        String from = rs.getString("From"); 
        String message = rs.getString("Message"); 
        String attachment = rs.getString("Attachment"); 
        int emailNo = rs.getInt("Email no"); 
        output.writeObject(from); 
        output.writeObject(message); // Send the username the 
                // message is from 
        output.writeObject(attachment); 
        output.writeObject(emailNo); 
        output.flush(); // and the message and flush the output 
            // stream 
        } 
       } catch (SQLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       try { 
        output.writeObject("END"); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } // Send an end message 
       try { 
        output.flush(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } // Flush the output stream 

       System.out.println(username // Tell the user someone is reading 
              // their messages 
        + " reading messages."); 

      } 

      if (userCommand.equals("QUIT")) // If the user command is quit 
      { 
       quit = true; // Set quit to true 
      } 

      if (userCommand.equals("DELETE MESSAGE")) // If the user command is 
                 // delete a message 
      { 
       int valueToDelete = 0; // Define local variables 

       try { 
        valueToDelete = Integer.parseInt((String) input.readObject()); 
       } catch (NumberFormatException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } catch (ClassNotFoundException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } // Receive the value to delete 
       Statement statement = null; 
       String delete = "DELETE FROM emails WHERE [Email No] = " 
        + valueToDelete + ""; 
       try { 
        statement = link.createStatement(); 
        statement.executeUpdate(delete); 
        link.commit(); 
       } catch (SQLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       System.out.println("Deleted message " + valueToDelete); // Tell 
                     // the 
                     // user a 
                     // message 
                     // has 
                     // been 
                     // deleted 
      } 
     } while (!quit); // Run while quit is false 

     System.out.println("Client Closed"); // Tell the user the client has // closed 
     } 

     private static void getFile(ObjectInputStream inStream, String fileType) 
      throws IOException, ClassNotFoundException { 

     byte[] byteArray = (byte[]) inStream.readObject(); 
     FileOutputStream mediaStream = null; 

     if (fileType.equals("Text File")) 
      mediaStream = new FileOutputStream("file.txt"); 
     else if (fileType.equals("Image")) 
      mediaStream = new FileOutputStream("file.gif"); 
     else if (fileType.equals("Movie")) 
      mediaStream = new FileOutputStream("file.mpeg"); 

     mediaStream.write(byteArray); 
     } 
    } 
} 
+1

을 차단합니다 "New client accepted. \ nRUNNING"을 인쇄하지만 "RUNNING CLIENT HANDLER"는 절대로 작동하지 않습니까? –

+1

이유는 http://stackoverflow.com/questions/10388253/client-server-objectinputstream-error/ – Attila

+0

과 동일합니다. 로컬 포트와 물건을 알려주지 만 결코 지나치지는 않는 클라이언트를 인쇄합니다. – AC3112

답변

0

그것은 그래서 당신이 말하고있는 것은 프로그램이다 ... 따라서 당신이 실제로 스레드를 실행에 결코, See also