I have the following server called Server.class and what exactly does, it receives text from the client and then sends that exact text back to the client. I'm just learning and I used the server from this website http://www.javaworld.com/article/2077322/core-java/core-java-sockets-programming-in-java-a-tutorial.html. The Client in my case is the browser so i don't need to implement it.
What I want to get is when a client asks for a file like: localhost:8888/myfile.txt
I should give him back that file, so he can download it or see it from the browser.
I tried to use a BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));
is
is a variable from InputStream
So now i can know what the client introduced doing String clientData = br.readLine()
But how can I get the file (myfile.txt) from that string and return that file so it can be observed or downloaded in the browser??
The Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String args[]) {
// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 8888
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(8888);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readLine();
os.println(line);
}
}
catch (IOException e) {
System.out.println(e);
}
}
}