serversocket - DataInputStream giving java.io.EOFException -
i have created small cli client-server application. once server loaded client can connect , send commands server.
the first command list of files server loaded with.
once socket connection established. request user enter 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 command: "); outputstream outtoserver = client.getoutputstream(); dataoutputstream out = new dataoutputstream(outtoserver); out.writeutf(command);
then server capture user's command , send appropriate replies.
severapp.java -
socket server = serversocket.accept(); datainputstream in = new datainputstream(server.getinputstream()); switch (in.readutf()){ case "list": (string filename : files) { out.writeutf(filename); } out.flush(); } server.close();
next 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
arraylist keep list of files loaded sever. when client sends list
command sever, need send array of strings (list of file names) back. app have more commands.
now when such request list of files , trows java.io.eofexception
while((value = in.readutf()) != null) {
how fix ?
edit (solution) ---
http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
notice datastreams detects end-of-file condition catching eofexception, instead of testing invalid return value. implementations of datainput methods use eofexception instead of return values.
try { while (true) { system.out.println(in.readutf()); } } catch (eofexception e) { }
the method readutf never return null. instead, should do:
while(in.available()>0) { string value = in.readutf();
looking @ javadocs, eofexception thrown if input stream reaches end before reading bytes.
Comments
Post a Comment