0

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);
        }
    }
}
Some Díaz
  • 51
  • 2
  • 11
  • Possible duplicate of [how to achieve transfer file between client and server using java socket](http://stackoverflow.com/questions/4687615/how-to-achieve-transfer-file-between-client-and-server-using-java-socket) – Ravi Ranjan Mar 05 '16 at 13:33
  • This is sending the file manually but in my case is the one that the client wants. – Some Díaz Mar 05 '16 at 13:37
  • If your client is a browser, then using a Socket is not enough: you need to implement an HTTP stack, with is not an easy task. – Jérémie B Mar 05 '16 at 13:38
  • You should probably use Spring MVC to make your like easier in that case. – Benoit Vanalderweireldt Mar 05 '16 at 14:44

0 Answers0