小さな CLI クライアント サーバー アプリケーションを作成しました。サーバーがロードされると、クライアントはサーバーに接続してコマンドをサーバーに送信できます。
最初のコマンドは、サーバーにロードされているファイルのリストを取得することです。
ソケット接続が確立されたら。ユーザーにコマンドを入力するように要求します。
ClientApp.java
Socket client = new Socket(serverName, serverPort);
Console c = System.console();
if (c == null) {
System.err.println("No console!");
System.exit(1);
}
String command = c.readLine("Enter a command: ");
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(command);
次に、サーバーはユーザーのコマンドをキャプチャし、適切な応答を送信します。
ServerApp.java -
Socket server = serverSocket.accept();
DataInputStream in = new DataInputStream(server.getInputStream());
switch (in.readUTF()){
case "list":
for (String fileName : files) {
out.writeUTF(fileName);
}
out.flush();
}
server.close();
次に、クライアントはサーバーの応答を取得します -
ClientApp.java
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
String value;
while((value = in.readUTF()) != null) {
System.out.println(value);
}
client.close();
files
サーバーにロードされたファイルのリストを保持するArrayListです。クライアントlist
がサーバーにコマンドを送信するとき、文字列の配列 (ファイル名のリスト) を送り返す必要があります。同様に、アプリにはより多くのコマンドがあります。
今、私がそのようなリクエストを行うと、ファイルとトローのリストを取得しjava.io.EOFException
ますwhile((value = in.readUTF()) != null) {
これを修正するには?
編集 (ソリューション) ---
http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
DataStreams は、無効な戻り値をテストする代わりに、EOFException をキャッチすることによってファイルの終わりの状態を検出することに注意してください。DataInput メソッドのすべての実装は、戻り値の代わりに EOFException を使用します。
try {
while (true) {
System.out.println(in.readUTF());
}
} catch (EOFException e) {
}