Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Client input Stream

  1. #1
    Junior Member
    Join Date
    Dec 2009
    Thanked 0 Times in 0 Posts

    Default Client input Stream


    ok well i have created a server/client program. The only problem is that my client keeps freezing. The only reason that i can tell why it freezes is because its recieving more data from the server than what it should. I have however stepped through the code on the server and everything seems to work precisely. I am really puzzled about this.

    this is my code for my server:
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    class ServerThread implements Runnable {
        private Server server = null;
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;
        private long start;
        private File file;          //create new string called file
        private String name;
         * constructor for the server thread.
         * @param s    socket from Multiserver
         * @param printIA
         * @param myHandler1  instance of when the Server form was created
         * @throws IOException  IOException for creating the bufferedReader and
         * Printwriter
        public ServerThread(Socket s, Server myHandler1) throws IOException {
            socket = s;
            server = myHandler1;
            name = null;
            in = new BufferedReader(new InputStreamReader(socket.getInputStream())); /*
            create new buffereed reader of socket*/
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            /*create new printwriter of socket*/
            Thread thisThread = new Thread(this);  //create new thread
            thisThread.start();         //start new thread
        } // end of constructor method
         * This thread is run to send the list of files to the client. As well as
         * transfering the file and the statistics of the transfer
        public void run() {
            ArrayList arrayFiles = new ArrayList();                //create arrayList to store filenames
            File folder = new File(server.getFilePath());               //get directory of files set by the user
            File[] listOfFiles = folder.listFiles();                // get all the files in the directory
            for (int i = 0; i < listOfFiles.length; i++) {          //create loop to check fiiles validate
                if (listOfFiles[i].isFile()) {                      //make sure its a file and not a subdirectory
                    String fileName = listOfFiles[i].getName();     //put file name into string
            out.println(arrayFiles);   // send the length of the files to the client
            try {
                while (true) {  //create loop so client can transfer more than one file at once
                    String close = in.readLine(); //get message from client for closing the connection or getting file
                    if (close.equals("close")) {    //check if message equals "close"
                        socket.close();    //close the socket
                        break;  //break from while loop
                    } else {
                        String fileName = in.readLine();  //get the name of the file the client wants
                        for (int i = 0; i < arrayFiles.size(); i++) {  /*loop until we find the
                             *position of the file name in the directory*/
                            name = arrayFiles.get(i).toString(); //place name of current file into file
                            if (name.equals(fileName)) {  //check if the name matches the name of the file the client wants
                                file = listOfFiles[i];    //place file into a File called file
                        long fileSize = file.length();   //get length of file and place in fileSize
                        out.println(fileSize);       //send the filesize to the client
                        long size=0;
                        FileInputStream fileInput = new FileInputStream(file);  //create fileInputStream of file
                        DataOutputStream stream = new DataOutputStream(socket.getOutputStream()); //creat DataOutputStream of the socket
                        byte[] bb = new byte[10000];   //create a byte that stores 10000 bytes
                        start = System.currentTimeMillis();  //get the current time in milliseconds
                        while (true) {                        //loop untill file is sent
                            int result = fileInput.read(bb);   //read 10000 bytes of the file into result
                            if (result == -1) {              //check if end of file has been
                                break;                          //exit while loop
                            stream.write(bb, 0, result);       //send 10000 bytes of file to the
                        long time = System.currentTimeMillis() - start; //get the current time and subtract from start time to get transfer time
                        server.addCount();   //increment the count of files sent by the server
                        int count = server.transferCount();  //get the transfer count from the server
                        float fileRate = fileSize / time;  //get the bit rate of the file transfer
                        server.addRate(fileRate);          //add the bit rate to the overall bit rate of the server
                        float serverRate = server.getRate();  //get the overall server rate
                        server.addSize(fileSize);   //add the transfered file size to the total transfered bytes of the server
                        long bytesSent = server.getFileSize();   //get the total transfered bytes of the server
                        /*This next line combines all the statistics needed for the client
                         * The semi colons are added so the client can easily split up the information
                        String info = Long.toString(time) + ";" +
                                Long.toString(fileSize) + ";" +
                                Float.toString(fileRate) + ";" +
                                Integer.toString(count) + ";" +
                                Float.toString(serverRate) + ";" +
                                Long.toString(bytesSent) + ";";
                        out.println(info);   //sends the info to the clienty
                    }  //end of else statement
                }  //end of while loop
            } catch (IOException ex)

    this is my client

    import javax.swing.*;
    import java.net.*;
    import java.io.*;
     * Start of the Connect class
     * @author Andrew Gisler, Matthew Clark, Matthew George
    public class Connect {
        Socket socket;                //create a socket variable
        BufferedReader in;          //create a BufferedReader variable
        PrintWriter out;            //create a PrintWriter variable
         * constructor of Connect
        private boolean status;
        public Connect() {
     * This method starst the connection to the server.
     * It also displays errors if connection was unsuccessful or if an invalid host
     * name was entered
     * @param address  this is the server address the user entered in
     * @param port    this is the port number the user entered in
     * @return      if the connection was successful or failed
     * @throws IOException
        public boolean startConnection(String address, String port) throws IOException {
            Client cl = new Client();  //create new instance of the Client class
            boolean status = false;    //set the status of the connection to false
            try {
                InetAddress inet = InetAddress.getByName(address);  //check if the address is valid
                socket = new Socket(inet, Integer.parseInt(port));  //create sockeet
                status = true;                                          //set status to true
            } catch (UnknownHostException ex) {      //catch if host name is invalid
                JOptionPane.showMessageDialog(cl, "Invalid host: Please check host name"); //displays error for invalid host
            } catch (ConnectException ex) {   //catch if connection was unsuccessful
                JOptionPane.showMessageDialog(cl, "Can't Connect - try again");  //displays error for connection failure
                } catch (IOException ex) {
            return status;                                              //return status of connection to client class
         * This method gets the file from the server.
         * @param fileName  is the selected filename the user wants from the server
         * @param path is the location of where the file should be created
         * @return the statistics of the tranfer to the client class
         * @throws IOException
        public String getFile(String fileName, String path) throws IOException {
            String newFileName = fileExists(path,fileName);
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);  //create a new instance of PrintWriter based on the socket connection
            out.println(fileName);  //send out the filname across the socket to the server
            String filesize = in.readLine();        //get the size of the file from the server
            long fileSize = Long.parseLong(filesize.trim());         //convert the filesize from a string to a long datatype
            DataInputStream dataInput = new DataInputStream(socket.getInputStream()); //create a new instance of a DataInputStream in order to get data from server
            FileOutputStream fileOutput = new FileOutputStream(path.trim() + "\\" + newFileName.trim()); //create new instance of FileOutputStream to write the file to the clients computer
            byte[] bb = new byte[10000];           //create a new instance of a byte
            while (true) {
                int result = dataInput.read(bb);     //read 10000 bytes and place bytes in variable called result
                fileOutput.write(bb, 0, result);        //write a file on input
                if (fileSize <= result) {               //check if result is equal to the filesize
                    break;                              //break while loop
                fileSize -= result;                  //subtract result from fileSize
            int result2 =dataInput.read(bb);
            String info = in.readLine();  //read in the statistics for the transfer fromt the server
            return info;    //return the statistics to the client
     * This method is used to check if the destination of images already contains
     * the file names. If the file already exists then it adds a number to the name
     * to make the file transfer unique
     * @param path is the selected path from the user
     * @param fileName is the filename the user would like
     * @return the new filename
        public String fileExists(String path, String fileName) {
            File fileCheck = new File(path.trim() + "\\" + fileName.trim());  //make a new of the file
            int count = 0;              //create count and set to 0
            String newFileName = "";        //set newFilename to ""
            String[] nameSplit =fileName.split("\\.");  // split the fileName and the extention of the name into a String array
            File folder = new File(path);               //get directory of files set by the user
            File[] listOfFiles = folder.listFiles();   //get list of files in the directory
                if (fileCheck.exists()) {    //check if origanl file exists
                } else {
                    newFileName = fileName;  //copy name of origanl file to the newFilename string
                for (int i = 0; i < listOfFiles.length; i++) {          //create loop to check files validate
                    String listName = listOfFiles[i].getName();        //get the name of the file in the directory
                    String[] fileSplit = listName.split("\\.");         //split the name from the extension into an array
                    boolean containsNumber = fileSplit[0].contains(Integer.toString(i));    //check if the name contains an integer
                    boolean containsName = fileSplit[0].contains(fileName);   //check if the name contains the name
                    if (containsName==true)                     //check if the name is true
                        if (containsNumber==true) {             //check if there is a number
                        count++;                        //increment the count
            if (newFileName.equals(fileName)){   //check if fileName equals newFileName
             newFileName = nameSplit[0] + "(" + Integer.toString(count) + ")" + "." + nameSplit[1];  //add the count to the filename
             return newFileName;   //return the newFileName
     * This method gets list of files fromt the server
     * @return the list of files to the client class
     * @throws IOException
        public String getList() throws IOException {
            String arrayFiles = null;                     //create new array and set to null
            in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //create new buffered reader
            try {
                arrayFiles = in.readLine();   //get list of files
            } catch (NumberFormatException nFE) {
            return arrayFiles;              //return list of files to client class
         * close the connection when the clients disconnect button is pressed or
         * window is closed
         * @throws IOException
        public void closeConnection() throws IOException {
            try {
                if (socket.isConnected() == true) {  //check if the socket is connected
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                    out.println("close"); //send message to server to close socket
                    socket.close();  //close socket
            } catch (RuntimeException e) {


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Thanked 833 Times in 772 Posts
    Blog Entries

    Default Re: Client input Stream

    I guessing it has something to do with the following:

    while (true) {
                int result = dataInput.read(bb);     //read 10000 bytes and place bytes in variable called result
                fileOutput.write(bb, 0, result);        //write a file on input
                if (fileSize <= result) {               //check if result is equal to the filesize
                    break;                              //break while loop
                fileSize -= result;                  //subtract result from fileSize

    If there is no more data to read and an end of file is reached, read() will return -1, in which case the code won't call the break and go back to read(), which may block indefinitely while its waiting for more data which won't be retrieved. (Also check the call to write to a file, which will always write out at offset 0 - not sure if this is what you want)

Similar Threads

  1. RMI over SSL Client application
    By boilerchicken in forum Java Networking
    Replies: 0
    Last Post: November 10th, 2009, 07:52 AM
  2. Values of Input
    By chronoz13 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: November 8th, 2009, 03:46 AM
  3. Redirect error and output stream using java program
    By leenabora in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: June 16th, 2009, 04:12 AM
  4. [SOLVED] web client
    By 5723 in forum File I/O & Other I/O Streams
    Replies: 8
    Last Post: June 10th, 2009, 04:44 PM
  5. How to write switch statement inside if statement?
    By Rezz in forum Loops & Control Statements
    Replies: 6
    Last Post: June 11th, 2008, 11:27 AM