0

I'm trying to make some program which includes file transfers. Of course i have to do some client-server communication by using character streams and i need to use byte streams as well to transfer files. The problem appears when i'm using println method form PrintWriter and readLine from BufferedReader because readLine reads line but lefts '\n' on stream and that causes problem(I'm not 100% sure that that is the problem) after i try to use byte stream to transfer files. So i need to get rid off that character and i tried that by using read method from Reader class and i wasn't successful with that. The code works perfectly without using character streamers. Pay attention how is sizeOfFile inflenced by calls of readLine.

SERVER

import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private static int SERVER_PORT = 9999;
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(SERVER_PORT);
            System.out.println("Server je pokrenut");
            while (true) {
                Socket sock = ss.accept();
                new MultithreadServer(sock);
            }
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

SERVER THREAD

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

public class MultithreadServer extends Thread {
    private Socket sock;
    BufferedReader inChar;
    PrintWriter outChar;
    BufferedInputStream in;
    BufferedOutputStream out;
    DataOutputStream outByte;
    public MultithreadServer(Socket sock) throws Exception {
        this.sock = sock;
        inChar = new BufferedReader(
            new InputStreamReader(sock.getInputStream()));
        outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            sock.getOutputStream())), true);
        in = new BufferedInputStream(sock.getInputStream());
        out = new BufferedOutputStream(sock.getOutputStream());
        outByte = new DataOutputStream(sock.getOutputStream());
        start();
    }
    public void run() {
        try {
            String request = inChar.readLine();
            System.out.println("Fajl: " + request);
            File file = new File(request);
            BufferedInputStream in = new BufferedInputStream(
                new FileInputStream(file));
            long sizeOfFile = (long) file.length();

            outChar.println("SOME_MESSAGE"); //PROBLEM

            byte[] buffer = new byte[4096];
            int len = 0;
            outByte.writeLong(sizeOfFile);
            long totalyTransfered = 0;
            while ((len = in.read(buffer, 0, buffer.length)) !=-1) {
                out.write(buffer, 0, len);
                totalyTransfered += len;
            }
            System.out.println("Total:" + totalyTransfered);
            out.flush();
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

CLIENT

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

public class ClientServer {
 static int SERVER_PORT = 9999;
 public static void main(String[] args) throws Exception {
 InetAddress address = InetAddress.getByName("127.0.0.1");
 Socket sock = new Socket(address, SERVER_PORT);
  PrintWriter out = new PrintWriter(new BufferedWriter(
   new OutputStreamWriter(sock.getOutputStream())), true);
  BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  Reader readChar = new InputStreamReader(sock.getInputStream());

 System.out.println("File:");   // choosing file from server
 Scanner consoleInput = new Scanner(System.in);
 String file = consoleInput.next();
 out.println(file);

 DataInputStream in = new DataInputStream(sock.getInputStream());

 System.out.println("Type name of file:");  //choosing name for file on client
 String newFile = consoleInput.next();

 OutputStream outByte = new FileOutputStream(newFile);
 byte[] buffer = new byte[4096];


 System.out.println("aa"+inChar.readLine()+"aa");   //PROBLEM
 System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT");  //TRYING TO FIX THE  PROBLEM
   //       in.read(); in.read();                      // DIFFERENT TRY
   long sizeOfFile= in.readLong();                    // BUT IT STILL HAS INFLUENCE OF       sizeOfFile
 System.out.println("Size of file:" + sizeOfFile);

 long totalyTransfered= 0;
 int len = 0;
 while ((len = in.read(buffer,0,buffer.length)) != -1) {
  outByte.write(buffer, 0, len);
  System.out.println("In one pass:" + len);
  sizeOfFile-=len;
  totalyTransfered+=len;
 System.out.println("Total:" + totalyTransfered);
 if (sizeOfFile<=0)break; 
  }
   System.out.println("Available: "+in.available());
  outByte.flush();
  outByte.close();

}
}
user1610362
  • 637
  • 2
  • 9
  • 26

1 Answers1

0

I modified your code and made a file transfer successfully, am sorry that I didnt have time to figure the issue in your code, I thought your code was not simple :).

But please find below your modified code and its quite simple and I refered this code from here

class Server:
No changes

class ClientServer:

public class ClientServer {

    static int SERVER_PORT = 9999;

    private static final String fileOutput = "C:\\testout.pdf";

    public static void main(String[] args) throws Exception {
        InetAddress address = InetAddress.getByName("127.0.0.1");

        Socket sock = new Socket(address, SERVER_PORT);
        InputStream is = sock.getInputStream();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(sock.getOutputStream())), true);
        BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        Reader readChar = new InputStreamReader(sock.getInputStream());

        System.out.println("File:");   // choosing file from server
        Scanner consoleInput = new Scanner(System.in);
        String file = consoleInput.next();
        out.println(file);

        DataInputStream in = new DataInputStream(sock.getInputStream());

        System.out.println("Type name of file:");  //choosing name for file on client
        //String newFile = consoleInput.next();
        //
        //      OutputStream outByte = new FileOutputStream(newFile);
        //      byte[] buffer = new byte[4096];
        //
        //
        //      System.out.println("aa"+inChar.readLine()+"aa");   //PROBLEM
        //      System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT");  //TRYING TO FIX THE  PROBLEM
        //      //       in.read(); in.read();                      // DIFFERENT TRY
        //      long sizeOfFile= in.readLong();                    // BUT IT STILL HAS INFLUENCE OF       sizeOfFile
        //      System.out.println("Size of file:" + sizeOfFile);
        //
        //      long totalyTransfered= 0;
        //      int len = 0;
        //      while ((len = in.read(buffer,0,buffer.length)) != -1) {
        //          outByte.write(buffer, 0, len);
        //          System.out.println("In one pass:" + len);
        //          sizeOfFile-=len;
        //          totalyTransfered+=len;
        //          System.out.println("Total:" + totalyTransfered);
        //          if (sizeOfFile<=0)break; 
        //      }
        //      System.out.println("Available: "+in.available());
        //      outByte.flush();
        //      outByte.close();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        int bytesRead;
        try {
            byte[] aByte = new byte[1];
            fos = new FileOutputStream(fileOutput);
            bos = new BufferedOutputStream(fos);

            bytesRead = is.read(aByte, 0, aByte.length);

            do {
                baos.write(aByte);
                bytesRead = is.read(aByte);
            } while (bytesRead != -1);

            bos.write(baos.toByteArray());
            bos.flush();
            bos.close();
            sock.close();
        } catch (IOException ex) {
            // Do exception handling
        }
    }
}

class MutilthreadServer:

public class MultithreadServer extends Thread {

    private Socket sock;
    BufferedReader inChar;
    PrintWriter outChar;
    BufferedInputStream in;
    BufferedOutputStream out;
    DataOutputStream outByte;

    public MultithreadServer(Socket sock) throws Exception {
        this.sock = sock;
        inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
        in = new BufferedInputStream(sock.getInputStream());
        out = new BufferedOutputStream(sock.getOutputStream());
        outByte = new DataOutputStream(sock.getOutputStream());
        start();
    }

    public void run() {
        try {
            String request = inChar.readLine();
            System.out.println("Fajl: " + request);
            File file = new File(request);
            BufferedInputStream in = new BufferedInputStream(
                    new FileInputStream(file));

            byte[] buffer = new byte[(int) file.length()];

            FileInputStream fis = null;

            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException ex) {
                // Do exception handling
            }
            BufferedInputStream bis = new BufferedInputStream(fis);
            //long sizeOfFile = (long) file.length();

            //outChar.println("SOME_MESSAGE"); //PROBLEM

            //byte[] buffer = new byte[4096];
            try {
                bis.read(buffer, 0, buffer.length);
                out.write(buffer, 0, buffer.length);
                out.flush();
                out.close();
                sock.close();

                // File sent, exit the main method
                return;
            } catch (IOException ex) {
                // Do exception handling
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Note: There are few unused lines of code, please remove it. Hope it helps on a Sunday :) !!!

Community
  • 1
  • 1
likeToCode
  • 852
  • 2
  • 10
  • 20
  • As i said my program works perfectly without usage of character streamers and problems occur when i send chars before data transfer.If you delete this line outChar.println("SOME_MESSAGE"); //PROBLEM from server thread and System.out.println("aa"+inChar.readLine()+"aa"); //PROBLEM System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT"); from client the code will work. You delete character streamers but i need them for client-server communication, but thanks for code simplification. – user1610362 Aug 19 '12 at 21:06
  • So what i want to say is if you add in your code outChar.println("SOME_MESSAGE"); in server thread and System.out.println(inChar.readLine()); in client you program wont work. – user1610362 Aug 19 '12 at 21:15