2014-03-01 1 views
0

DataInput/OutputStream을 통해 개체를 보내는 간단한 클라이언트/서버 모델을 설정하려고합니다. 내 클라이언트 코드는 다음과 같습니다클라이언트/서버; 클라이언트 코드 완료 후 서버가 EOFException을 throw합니다.

서버 측에서
public static void main(String[] args) { 
    final String HOST_NAME = "localhost"; 
    final int PORT_NUMBER = 9090; 

    Card card = new Card(0, 0, 0, 0); 

    try { 
     Socket socket = new Socket(HOST_NAME, PORT_NUMBER); 
     ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); 
     ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); 

     output.writeObject(card); 
     card = new Card(1, 1, 1, 1); 
     output.writeObject(card); 
     output.writeObject(null); 

     output.close(); 
     input.close(); 
     socket.close(); 
    } catch (UnknownHostException e) { 
     System.err.println("Can not recognize: " + HOST_NAME); 
    } catch (IOException e) { 
     System.err.println("Bad port number: " + PORT_NUMBER); 
    } 
} 

, 나는 코드의 몇 가지 변화를 시도, 현재의는 다음과 같습니다

static boolean listening = true; 

public static void main(String args[]) throws IOException { 
    ServerSocket serverSocket = new ServerSocket(9090); 
    while (listening) { 
     Socket socket = serverSocket.accept(); 
     try { 
      ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); 
      ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); 

      while ((card = (Card) input.readObject()) != null) { 
       for (int feature : card.getFeatures()) { 
        System.out.println(feature + " "); 
       } 
      } 

      output.close(); 
      input.close(); 
      socket.close(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

이 내가 원하는 무엇의 단순화 및 작업 버전입니다 . 나는 서버가 새로운 카드 객체를 계속 듣고 null 객체를 얻을 때까지 그들의 기능을 인쇄하기를 원합니다. 그러나 이것을 실행하면 첫 번째 카드의 기능이 인쇄 된 다음 서버 끝에서 즉시 EOFException이 발생합니다.

나는 finally을 사용하여 while에서 탈주하는 것을 포함하여 다양한 변형을 시도했지만 모든 경우에 첫 번째 카드를 인쇄하지 않습니다. 클라이언트가 소켓을 닫을 때까지 서버가 계속 수신 및 수신 카드를 유지할 것이라고 어떻게 보장 할 수 있습니까?

답변

1
while ((card = (Card) input.readObject()) != null) { 

이 루프를 종료 자신에게 null을 보낼 계획하지 않는 한,이 스트림의 마지막에 null를 반환하지 않는 ObjectInputStream.readObject() 방법을 읽을 수있는 유효한 방법이 아니다 : 그것은 그래서 EOFException.를 던졌습니다 , 당신은 그것을 잡아야한다. 따라서 루프 조건은 실제로 while (true),이어야하며 readObject() 호출은 루프 내부에 있어야합니다. 그럼 당신은 루프 내에서

try 
{ 
    card = (Card)input.readObject(); 
    // ... 
} 
catch (EOFException) 
{ 
    break; 
} 

이 있거나 안에 지금 break;를 필요로하지 않는 catch (EOFException)와 try/catch 블록을 루프 을해야 하나.

+0

나는이 솔루션이 마음에 든다. 나는 당신이 서버에'null '을 먹여서 언급했듯이 작동하도록 만들었다. – mike

+0

이것은 일시적인 해결책 일뿐만 아니라 다른 이유로 인해 null을 보내지 못하게합니다. – EJP

관련 문제