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
에서 탈주하는 것을 포함하여 다양한 변형을 시도했지만 모든 경우에 첫 번째 카드를 인쇄하지 않습니다. 클라이언트가 소켓을 닫을 때까지 서버가 계속 수신 및 수신 카드를 유지할 것이라고 어떻게 보장 할 수 있습니까?
나는이 솔루션이 마음에 든다. 나는 당신이 서버에'null '을 먹여서 언급했듯이 작동하도록 만들었다. – mike
이것은 일시적인 해결책 일뿐만 아니라 다른 이유로 인해 null을 보내지 못하게합니다. – EJP