2014-03-05 2 views
0

입력을 입력 할 때 루프가 실패하는 동안 클라이언트에서 입력을 읽는 데 문제가 있습니다. 서버 클래스에서 while 문을 사용하지 않고 if 문을 사용할 때마다 완벽하게 작동합니다. 아무도 왜 이것이 실패 할 수 있는지를 지적 해 줄 수 있습니까?소켓 읽기가 자바에서

서버 클래스 :

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

public class Server { 

    public static void main(String[] args) throws Exception 
    { 
     Server myServer = new Server(); 
     myServer.run(); 
    } 

    public void run() throws Exception 
    { 

     //Initializes the port the serverSocket will be on 
     ServerSocket serverSocket = new ServerSocket(9999); 
     System.out.println("The Server is waiting for a client on port 9999"); 
     //Accepts the connection for the client socket 
     Socket socket = serverSocket.accept(); 

     InputStreamReader ir = new InputStreamReader(socket.getInputStream()); 
     BufferedReader br = new BufferedReader(ir); 
     String message = br.readLine(); 
     //Confirms that the message was received 
     System.out.println(message); 

    //When this while is here. The match fails and it goes to the else statement. 
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO. 

    while(message != null) 
    { 
      if(message.equals("HELLO")) 
      { 
       PrintStream ps = new PrintStream(socket.getOutputStream()); 
       ps.println("Received our hello message."); 
      } 
      else 
      { 
       PrintStream ps = new PrintStream(socket.getOutputStream()); 
       ps.println("Did not receive your hello message"); 
      } 
     } 
    } 
} 

클라이언트 클래스 : 당신이 무한 루프 그래서

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

public class Client { 

    public static void main(String[] args) throws Exception 
    { 
     Client myClient = new Client(); 
     myClient.run(); 
    } 

    public void run() throws Exception 
    { 
     Socket clientSocket = new Socket("localhost", 9999); 
     //Sends message to the server 
     PrintStream ps = new PrintStream(clientSocket.getOutputStream()); 
     Scanner scan = new Scanner(System.in); 
     String cMessage = scan.nextLine(); 
     ps.println(cMessage); 
     //Reads and displays response from server 
     InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream()); 
     BufferedReader br = new BufferedReader(ir); 
     String message = br.readLine(); 
     System.out.println(message);   
    } 

} 
+2

무엇이 작동하지 않습니까? 나는 당신의 코드를 컴파일하고 "안녕하세요 메시지를 받았습니다." 클라이언트에 HELLO를 입력 한 후 –

+0

while 루프를 꺼낼 때 작동합니다. 내가 HELLO를 받아서 서버 창에 출력 할 때 아무것도 남기지 않으면 예외가 생깁니다. – Shawn

+1

좋은 연습은 프로그램 끝에서 모든 소켓과 독자를 닫는 것입니다. –

답변

1

서버 측에서만 반복되지만 클라이언트 측에서 반복하는 것을 잊어 버렸습니다. 빠른 수정을 수행했으며 연결을 닫는 데 도움을줍니다. 당신처럼 루프를 사용 Server.java

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

public class Server { 

    public static void main(String[] args) throws Exception 
    { 
     Server myServer = new Server(); 
     myServer.run(); 
    } 

    public void run() throws Exception 
    { 

     //Initializes the port the serverSocket will be on 
     ServerSocket serverSocket = new ServerSocket(9999); 
     System.out.println("The Server is waiting for a client on port 9999"); 
     //Accepts the connection for the client socket 
     Socket socket = serverSocket.accept(); 

     InputStreamReader ir = new InputStreamReader(socket.getInputStream()); 
     BufferedReader br = new BufferedReader(ir); 
     String message; 
     //= br.readLine(); 
     //Confirms that the message was received 

    //When this while is here. The match fails and it goes to the else statement. 
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO. 
     PrintStream ps = new PrintStream(socket.getOutputStream()); 
     while((message =br.readLine())!=null) 
     { 
      System.out.println(message); 
       if(message.equals("HELLO")) 
       { 

        ps.println("Received our hello message."); 
       } 
       if(message.equals("END")) 
       { 
        ps.println("Client ended the connection"); 
        break; 
       } 
       else 
       { 

        ps.println("Did not receive your hello message"); 
       } 
     } 
     ps.close(); 
     br.close(); 
     ir.close(); 
     serverSocket.close(); 
    } 
} 

Client.java

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

public class Client { 

    public static void main(String[] args) throws Exception 
    { 
     Client myClient = new Client(); 
     myClient.run(); 

    } 

    public void run() throws Exception 
    { 
     Socket clientSocket = new Socket("localhost", 9999); 
     //Sends message to the server 
     PrintStream ps = new PrintStream(clientSocket.getOutputStream()); 
     Scanner scan = new Scanner(System.in); 
     String cMessage =""; 
     InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream()); 
     BufferedReader br = new BufferedReader(ir); 
     while(!(cMessage.trim().equals("END"))){ 
     cMessage = scan.nextLine(); 
     ps.println(cMessage); 
     //Reads and displays response from server 
     String message = br.readLine().trim(); 
     System.out.println(message); 
     } 
     br.close(); 
     ir.close(); 
     scan.close(); 
     ps.close(); 
     clientSocket.close(); 
    } 

} 
+0

신난다. 완벽하게 작동했다. 메시지 === BYE이면 다른 것을 추가해야했다. 도움을 주셔서 감사 드리며 답변으로 표시되어 있습니다. – Shawn

2

당신은 결코 while 루프 내부에 메시지를 수정하지 있습니다.

당신의 코드는 하나의 'HELLO'메시지를 전송 잘 작동하고

while((message = br.readLine()) != null)

+0

나는 클라이언트가 HELLO라고했을 때 그것을 시도했다. 서버가 그것을 받아서 서버 창에서 HELLO를 출력하고 아무 일도 일어나지 않는다. 클라이언트에서 서버로 다른 것을 입력하려고하면 인쇄되지 않습니다. – Shawn

+0

@Shawn, 아무 일도 일어나지 않을 것입니다. p.printline을 반복하는 것을 잊어 버리는 동안 br.readline 만 루프합니다. –

1

을보십시오. 그러나^Tyler가 지적한 것처럼 메시지를 계속 보내려면 while 루프에서 while ((message = br.readLine())! = null) '을 이동해야합니다.

+0

좋아, 그래서 while 문 (이 두 줄)으로 이동하면 다음과 같습니다. String message = br. readLine(); System.out.println (message); Received our hello 메시지를 출력 할 것입니다. 하지만 Server.run (줄 30) 및 Server.main (줄 9)에서 스레드 "main"java.lang.NullPointerException의 예외가 발생하지 않습니다. – Shawn

+0

Shawn, while (외부에서 br.readLine()을 제거하지 못했음) while 루프에서 사용하고 있습니다. 그래서 인쇄하고 while 회 돌이에 들어 가지 않습니다! <타일러에 대한 질문을 바탕으로> – user3329166

+0

방금 ​​while 루프에서 메시지를 읽어야한다고 말씀 드린 바 있습니다. 나는 그것을 명확하게하기 위해 나의 포스트를 편집 할 것이다! – user3329166

0

...

String line; 
while ((line = in.readLine()) != null) { 
    System.out.println(line); 
    sleep(in); 
    if(!in.ready()){ 
     break; 
    } 
} 

내가 알아 낸 사기꾼 방법이 있습니다.

private static void sleep(BufferedReader in) throws IOException { 
    long time = System.currentTimeMillis(); 
    while(System.currentTimeMillis()-time < 1000){ 
     if(in.ready()){ 
      break; 
     } 
    }  
} 

이 실수 할 수 있지만, 수 당신은 시간의 양을 기다립니다 그냥 BufferedReader의 경우 계속 확인 절전 방법을 만들 경우 "준비를." 그것이 그렇다면, 당신은 탈출 할 수 있지만, 다시 나올 때는 다시 확인하십시오. - 어쩌면 당신은 단지 두 번 검사하는 대신 부울을 반환 할 수 있지만 개념은 거기에 있습니다.

관련 문제