1

I know how to send a file from a server to a client but how do I send a textstring to the client where the client save the string as a file? Should I use PrintWriter for this issue?

This is the code for sending a file from server to client: Sending files through sockets

What I want to do is to (instead of sending a file), sending a String from the server and let the client receive it and save it as a file.

public class SocketFileExample {
    static void server() throws IOException {
        ServerSocket ss = new ServerSocket(3434);
        Socket socket = ss.accept();
        InputStream in = new FileInputStream("send.jpg");
        OutputStream out = socket.getOutputStream();
        copy(in, out);
        out.close();
        in.close();
    }

    static void client() throws IOException {
        Socket socket = new Socket("localhost", 3434);
        InputStream in = socket.getInputStream();
        OutputStream out = new FileOutputStream("recv.jpg");
        copy(in, out);
        out.close();
        in.close();
    }

    static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[8192];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
    }

    public static void main(String[] args) throws IOException {
        new Thread() {
            public void run() {
                try {
                    server();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        client();
    }
}
Community
  • 1
  • 1
java
  • 1,165
  • 1
  • 25
  • 50

1 Answers1

1

in that case use ObjectOutputStream at server side to write String and use ObjectInputStream at client side to read String coming from server..

so your server() method will look like this..

static void server() throws IOException {
    ServerSocket ss = new ServerSocket(3434);
    Socket socket = ss.accept();
    OutputStream out = socket.getOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(out);
    oout.writeObject("your string here");
    oout.close();
}

and client() method will look like this..

static void client() throws IOException, ClassNotFoundException {
    Socket socket = new Socket("localhost", 3434);
    InputStream in = socket.getInputStream();
    ObjectInputStream oin = new ObjectInputStream(in);
    String stringFromServer = (String) oin.readObject();
    FileWriter writer = new FileWriter("received.txt");
    writer.write(stringFromServer);
    in.close();
    writer.close();
}

also throw ClassNotFoundException in main method.

public static void main(String[] args) throws IOException, ClassNotFoundException {.......}

done...

ELITE
  • 5,815
  • 3
  • 19
  • 29