2014-06-20 4 views
0

안녕하세요 저는 메시지 전달을 사용하여 기본 로그인 서버를 작성하고 있습니다. 내 서버가하는 일은 파일 인 데이터베이스의 일부 클라이언트 검사에서 메시지를 수신하고 이에 따라 응답을 다시 전송하므로 텔넷에서 메시지를 보낼 때마다 내 서버가이를 받아들이고 응답하는 것을 볼 수 있습니다. 그것은 메시지를 다시 받아들이지 않습니다. 아래 코드는 내 숙제가 아닙니다.로그인 서버 웹 앱 java

package login; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.io.StreamCorruptedException; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.net.SocketException; 

public class Login { 

    public static void main(String[] args) { 

     Login login = new Login(); 

     new Thread(login.new ServerTask(null)).start(); 
     new Thread(login.new ClientTask("clientstart")).start(); 
    } 

    public String login(String userName, String password, String memberId) { 
     System.out.println("Entering login"); 
     boolean match = false; 
     try { 

      // created an file input stream and a buffered reader stream to read 
      // from the files 
      FileInputStream inputStream = new FileInputStream(
        "/home/rahulroc18/Desktop/database.txt"); 
      BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(inputStream)); 

      String strLine; 
      String[] dataReader; 
      dataReader = new String[10]; 
      String readData = ""; 

      // Loop through the end of the file and read the data line by line 
      // in order to store it into a string for further storage in the 
      // memory 

      while ((strLine = bufferedReader.readLine()) != null) { 
       readData = readData + strLine + ":"; 

      } 
      // split the string to store user name and password for storing in 
      // an array in alternate positions 

      dataReader = readData.split(":"); 
      // System.out.println(dataReader.length); 

      // loops through the array and checks the user name and passwords 
      // for 
      // the correct match sends the login successful if password is 
      // incorrect sends message password in correct else for no match 
      // sends check your credentials 

      for (int i = 0; i < dataReader.length; i++) { 
       if (userName.equals(dataReader[i])) { 
        match = true; 
        if (password.equals(dataReader[i + 1])) { 
         String message; 
         message = "Login Successfull" + " : " + userName 
           + " : " + password + " : " + memberId; 
         System.out 
           .println("Sending success message to client !!!"); 
         return message; 
         // send the transactions and data of whatever 
         // conversation has taken place till now 
         // System.out.println("for loop of login"); 
         // System.out.println("message to be sent back is: " + 
         // message); 
         // new Thread(new ClientTask(message)).start(); 
         // Send message to all users that this new user has 
         // joined the conversation 
         // System.out.println(message); 

        } else { 
         String message = ""; 
         message = "Password Incorrect"; 
         System.out.println("message to be sent back is: " 
           + message); 
         System.out.println(message); 
         return message; 
        } 

       } 
      } 
      if (!match) { 
       String message = ""; 
       message = "check your credentials"; 
       System.out.println("message to be sent back is: " + message); 
       return message; 
      } 

      inputStream.close(); 
     } catch (FileNotFoundException f) { 
      f.printStackTrace(); 
     } catch (IOException e) { 
      System.out.println(e); 

     } 

     System.out.println("Exiting login"); 
     return null; 
    } 

    class ServerTask implements Runnable { 

     String msgReceived; 

     public ServerTask(String message) { 
      msgReceived = message; 
     } 

     @Override 
     public void run() { 
      System.out.println("Server task started !!!"); 
      ServerSocket serverSocket = null; 

      try { 
       serverSocket = new ServerSocket(10000); 
       Socket clientSocket = null; 

       while (true) { 
        clientSocket = serverSocket.accept(); 

        BufferedReader buffer = new BufferedReader(
          new InputStreamReader(clientSocket.getInputStream())); 
        msgReceived = buffer.readLine(); 

        if (msgReceived.substring(0, 5).equals("login")) { 
         System.out.println("in if condition of server task"); 
         String finalMessage = login(
           msgReceived.substring(5, 10), 
           msgReceived.substring(10, 15), 
           msgReceived.substring(15)); 

         System.out.println("finalMessage is " + finalMessage); 

         OutputStream os = clientSocket.getOutputStream(); 
         OutputStreamWriter osw = new OutputStreamWriter(os); 
         BufferedWriter bw = new BufferedWriter(osw); 
         bw.write(finalMessage); 
         bw.flush(); 

        } else { 
         System.out.println("************"); 
         String message = "Client started successfully and startup message is recieved \n"; 

         OutputStream os = clientSocket.getOutputStream(); 
         OutputStreamWriter osw = new OutputStreamWriter(os); 
         BufferedWriter bw = new BufferedWriter(osw); 
         bw.write(message); 
         bw.flush(); 

        } 
       } 

      } catch (StreamCorruptedException sc) { 
       System.out.println(sc); 
      } catch (IOException i) { 
       i.printStackTrace(); 
      } 
     } 
    } 

    class ClientTask implements Runnable { 
     String msgToSend; 

     public ClientTask(String message) { 

      msgToSend = message; 

     } 

     @Override 
     public void run() { 

      Socket sock = new Socket(); 
      try { 

       sock = new Socket("127.0.0.1", 10000); 

       OutputStreamWriter out = new OutputStreamWriter(
         sock.getOutputStream()); 
       BufferedWriter buffer = new BufferedWriter(out); 

       buffer.write(msgToSend); 
       buffer.flush(); 
       sock.close(); 
       System.out.println("In client task .... message is " 
         + msgToSend); 

      } catch (SocketException s) { 

      } catch (IOException i) { 

      } 

     } 
    } 
} 
+0

코드를 모두 읽지는 않았지만'TaskServer.run'에서 스트림을 닫지 않으며 완료되면'clientSocket'도 보이지 않습니다. –

답변

0

코드에 많은 버그가 있습니다.

  1. 당신은 클라이언트와 무슨 일이 일어나고 있는지 코드에서 server.Now에 대해 별도의 클래스를 작성해야하는 것은 그 클라이언트 스레드가 서버 스레드보다는 처음 시작하면 일이 무엇인지 생각입니다.

  2. clientSocket = serverSocket.accept();이 메인 스레드에서 올 것이다 무엇이든지 당신이 serverSocket.accept();로부터받은 객체가 처리 할 메인 스레드에서 클라이언트의 요청과 새로 만든 스레드를 기다리는 다른 thread.So 서버에서 매개 변수로 올 것이다 클라이언트.

+0

안녕하세요 Sahil, 내 생각에 클래스를 만들면 문제가되지 않는다고 생각합니다. 특정 이유로이 코드를 언급하면이 코드가 최신 코드로 업데이트됩니다. 그것은 단지 한 번만 메시지를 받아들이고 응답을 한 번만 보내면 반복하지 않는다는 것입니다. – jack