import java.net.*;
import java.io.*;
import java.util.*;
public class TestClient extends Object {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 80);
PrintStream ps = new PrintStream(socket.getOutputStream(), true);
ps.println("send test.txt");
ps.println("4");
ps.println("test");
ps.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
For some reason when this client connects to the server I wrote, my server gets the "send test.txt" and it gets the "4" but it just drops "test" completely, I tried sending the exact same information to my server in telnet and it worked fine, I have no idea whats going wrong
ajtgarber wrote:Doesn't the close method also flush the stream?
Hmm yeah, that is the specified behaviour, but maybe an error occurred or something. Check http://stackoverflow.com/questions/2208 ... t-flushing, could that have something to do with your problem? Could you post the server code?
EDIT: Also, is their any particular reason why you're explicitly extending the Object class? All classes are implicitly subclasses of Object.
EDIT 2: Just to check, I wrote some extremely simple and ugly server code, and your clients seems to run fine against it. The problem may not lie with the client but with the server. Here's the ugly code that works:
...
else if(request.toLowerCase().startsWith("send ")) {
//issues
String placement = request.substring(4, request.length()).trim();
int num = scan.nextInt();
System.out.println(num);
File file = new File(placement);
FileOutputStream fos = new FileOutputStream(file);
for(int i = 0; i < num; i++) {
byte b = (byte)is.read();
System.out.print(b);
fos.write(b);
}
System.out.println("Finished Writing File!");
fos.flush();
fos.close();
}
...
^ The issue should be in there, (yes I know thats not the most efficient way to read from the network but right now I'm just
trying to get it to work...). The call to is.read() always returns -1.
I understand that this is a bit late, but I believe the problem you have experienced here is due to the Scanner class. Your client has called PrintStream#println, thus writing 4, followed by a newline character. Your server uses Scanner#nextInt in order to retrieve the value 4, but that method does not take the newline character that was written to the stream. This causes your next invocation of the Scanner#nextLine method to end on that leftover newline character, returning an empty String. You've chosen to close your client's connection to the server if no valid argument has been supplied, and that is why -1 is returned from your calls to InputStream#read afterward.