问题
I have created small CLI client-server application. Once the server is loaded the client can connect to it and send commands to the server.
The first command is to get list of files that server is loaded with.
Once the socket connection is established. I request user to enter a command.
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);
Then the server capture user's command and send appropriate replies.
SeverApp.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();
Next the client retrieve server's response -
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
is a ArrayList which i keep list of files loaded to the sever. When client sends list
command to the sever, i need to send array of strings (list of file names) back. Similarly app will have more commands.
Now when i do such request i get list of files and trows java.io.EOFException
from while((value = in.readUTF()) != null) {
How to fix this ?
EDIT (SOLUTION) ---
http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value. All implementations of DataInput methods use EOFException instead of return values.
try {
while (true) {
System.out.println(in.readUTF());
}
} catch (EOFException e) {
}
回答1:
The method readUTF will never return null. Instead, you should do:
while(in.available()>0) {
String value = in.readUTF();
Looking at javadocs, an EOFException is thrown if this input stream reaches the end before reading all the bytes.
回答2:
Use FilterInputStream.available().
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
String value;
while(in.available() > 0 && (value = in.readUTF()) != null) {
System.out.println(value);
}
...
回答3:
http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value. All implementations of DataInput methods use EOFException instead of return values.
try {
while (true) {
System.out.println(in.readUTF());
}
} catch (EOFException e) {
}
来源:https://stackoverflow.com/questions/23064917/datainputstream-giving-java-io-eofexception