0

I have written the following code for sending a text file from Client to Server using Sockets. I am new to both JAVA and Socket Programming. I feel I have got the socket concepts but Java Streams are quite confusing. Any help with the following code will be really helpful. PLEASE mention the mistake and Solution with reasoning.

The data seems to be sent just fine. But it is not received on the other end.

Server Code:

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(3000);
        while(true)
        {
            Socket convSocket = serverSocket.accept();
            System.out.println("connection accepted");

            BufferedReader in = new BufferedReader(new InputStreamReader(convSocket.getInputStream()));
            FileWriter fileOut = new FileWriter("/Users/aakashmalhotra/a.txt");

            int c;
            while( (c = in.read()) != -1){
                fileOut.write(c);
            }
            System.out.println("Transfer Done");
        }


    }
}

Client Code:

import java.io.*;
import java.net.Socket;

public class Client {
    public static void main(String[] argv) throws Exception {
        Socket clientSocket = new Socket("localhost", 3000); // create a socket

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        BufferedReader fileIn = new BufferedReader(new FileReader("/Users/aakashmalhotra/s.txt"));

        int c;
        while ((c = fileIn.read()) != -1) {
            out.write(c);
        }

    }
}
7
  • 1
    For one, you don't appear to be closing your readers or writers. Commented Sep 29, 2016 at 20:35
  • ... and for another throws Exception while not the cause of your problems, just shouldn't be done. In the least, catch exceptions and print stacktraces. Commented Sep 29, 2016 at 20:36
  • it will be more efficient, and more generalized, if you don't use readers, but use Streams. there's no need to go thru the hassle of converting bytes to characters if you are just copying them Commented Sep 29, 2016 at 20:36
  • you should also not read a byte at a time Commented Sep 29, 2016 at 20:36
  • Note: even with Sockets you have to remember the basic of closing any resources which need to be closed when you are done with them. Commented Sep 29, 2016 at 20:40

2 Answers 2

2

You need to .flush() or .close() the out writer on the client side.

Sign up to request clarification or add additional context in comments.

3 Comments

Or better yet use a try-with resources statement.
@flkes: there's a danger to that if you use threading and helper classes to do handle your streams.
@HovercraftFullOfEels For sure; In that case close it manually later to not kill the stream prematurely
0

IO objects, and especially streams, always need to be closed. This is because the OS is optimized for these type of operations, and it decides when the data should be sent on the pipe. Closing the resource make sure that the remainder of the data is sent. Example for the server side:

import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(3000);
        while (true) {
            Socket convSocket = serverSocket.accept();
            System.out.println("connection accepted");

            try (BufferedReader in = new BufferedReader(new InputStreamReader(convSocket.getInputStream()))) {
                try (FileWriter fileOut = new FileWriter("/Users/aakashmalhotra/a.txt")) {
                    int c;
                    while ((c = in.read()) != -1) {
                        fileOut.write(c);
                    }
                    System.out.println("Transfer Done");
                }
            }
        }
    }
}

It is important to note the usage of a try-with-resource statement, which ensures that the streams will be closed regardless of the outcome of your application. This guarantees that your stream will always be closed and that no resource will leak.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.