I am using linux and I have the server that receives an Input Stream from a client and returns only the file the client asks for from the browser.
It compiles perfectly but it returns nothing, i list all the steps i follow at the end to run the server and get the file.
The Server
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(9999);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = br.readLine();
System.out.println("File name = " + line);
//Deixem nomes el nom del File o fitxer
String fileName = line.replace("GET /", "");
fileName = fileName.replace(" HTTP/1.1", "");
System.out.println("File name is" + fileName);
out = new FileOutputStream(fileName);
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
System.out.println("Bytees "+count);
}
out.close();
in.close();
socket.close();
serverSocket.close();
}
}
As you can see I am using a method replace() to leave only the fileName. The client will be the browser who will ask for a file for example:
- Client wants a file hello.txt
localhost:9999/hello.txt
- The server is in the folder java/bin with name Server.class
- The file hello.txt is in the java/files
This how I execute my server from console:
- cd java/files
- java -cp ../bin Server [-p 9999]
But i dont receive Any file why? Am i doing something wrong??