Solved

IO Streams

Posted on 2001-06-26
8
354 Views
Last Modified: 2010-03-31
What is the best way to transfer files thru sockets?? What kind of streams can be used? Can anybody help me in this??
regards
0
Comment
Question by:anitharamunni
  • 3
  • 3
  • 2
8 Comments
 

Author Comment

by:anitharamunni
ID: 6228699
Can anybody tell me what is wrong with the following client and server code:



public class Client{

     static Socket socket;
     public static void main(String as[]){

          try{
               socket = new Socket("ecomserv",8888);
               DataInputStream dis = new DataInputStream(socket.getInputStream());

               FileWriter fw = new FileWriter(new File("proposal1.doc"));
               int data;
               while((data = dis.read()) != -1          ){
                    fw.write(data);
                    fw.flush();
               }
               fw.close();
          }
          catch(UnknownHostException e){
               System.out.println("Not Connected " + e );
               return;
          }
          catch(IOException ee){
               System.out.println("IO Exception " + ee );
               return;
          }
     }
}


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

public class Server{

     static ServerSocket listen;
     
     static PrintWriter pw;
     static DataInputStream dis;
     


     public static void main(String as[]){
          int data;
          try{
               listen = new ServerSocket(8888);
               Socket socket = listen.accept();
               pw = new PrintWriter(socket.getOutputStream());
               dis = new DataInputStream(socket.getInputStream());
               FileReader fr = new FileReader(new File("proposal1.doc"));
          //     BufferedReader br = new BufferedReader(fr);
               while((data = fr.read()) != -1 ){
                    pw.print(data);
                    pw.flush();
               }
               pw.close();
          }
          catch(Exception e){
               System.out.println("error " + e);
          }
     }
}



I am sending a file from the server to the client.
The file is transferring... but contains only junk... Can anybody explain what is going wrong here??
thankyou

0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6228889
Hi,

DataInputStream dis = new DataInputStream(socket.getInputStream());
// Not a bug, but you don't use DataInputStream specific functionality.
// Plain InputStream will work

int data;
while((data = dis.read()) != -1 ){
        fw.write(data);
// You need to cast data to byte: fw.write((byte)data);
        fw.flush();
// It's not a bug, but it slows you down. You don't really need to
// flush on each byte. I would even wrap FileOutputStream
// into BufferedOutputStream
}

FileReader fr = new FileReader(new File("proposal1.doc"));
//     BufferedReader br = new BufferedReader(fr);
while((data = fr.read()) != -1 ){
     pw.print(data);
// Now, you need to cast data to char
     pw.flush();
}
pw.close();

BTW, why your client and server are not symmetric? Why don't you use OutputStream on server side?
And server doesn't need to open InputStream--client doesn't send anything.
Better server would spawn new Thread upon accept return to serve several clients concurrently.

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com                                                         
0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6228895
> Better server would spawn new Thread upon accept return to serve several clients concurrently.
And wrap accept into infinite loop to serve more then one client.
0
 
LVL 1

Accepted Solution

by:
viswa081400 earned 10 total points
ID: 6229427
Hi!!
Your code looks correct but the problem is the way these streams work.

You use FileReader to read your file. FileReader and FileWriter read and write 16 bit characters. And FileInputStream and FileOutStreams read and write 8 bit characters.

If you inspect your code, you use FileReader in you server to read from the flat file (which reads and write a 16 bit character) and write it into the socket stream.

At the client end you use DataInputStream ( which extends FileInputStream ) to read from the input stream. Which reads only 8 bits at a time. Hence the data sent across is converted as junk. A quick check is just count the number of bytes you write out and number of bytes you read, if everthing is fine, they should be the same.

I have modified you code a little, so it uses data streams on client and server, and it works fine. Here is the modified code:

public class Client{

    static Socket socket;
    public static void main(String as[]){
     System.out.println( "Encoding : " + System.getProperty("file.encoding") );
         try{
              socket = new Socket("localhost",8888);
              DataInputStream dis = new DataInputStream(socket.getInputStream());

              FileOutputStream fos = new FileOutputStream( new File("proposal1.doc"));
              int data;
              while((data = dis.read()) != -1          ){


                   fos.write(data);
                   fos.flush();

              }

              fos.close();
              dis.close();
         }
         catch(UnknownHostException e){
              System.out.println("Not Connected " + e );
              return;
         }
         catch(IOException ee){
              System.out.println("IO Exception " + ee );
              return;
         }
    }
}

public class Server1{

    static ServerSocket listen;

    static PrintWriter pw;
    static DataInputStream dis;



    public static void main(String as[]){
         int data;
         try{
              listen = new ServerSocket(8888);
              Socket socket = listen.accept();
              pw = new PrintWriter(socket.getOutputStream());
              dis = new DataInputStream(socket.getInputStream());
              FileReader fr = new FileReader(new File("server.java"));
         //     BufferedReader br = new BufferedReader(fr);
                int count = 0;
              while((data = fr.read()) != -1 ){
                      count ++;
                   System.out.println( data + " : " + (char)data );
                   pw.print(data);
                   pw.flush();
              }
              pw.close();
              System.out.println( "Total number of char written : " + count );
         }
         catch(Exception e){
              System.out.println("error " + e);
         }
    }
}

Hope this helps!!
-viswa
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Expert Comment

by:viswa081400
ID: 6229432
oops!!
here is the modified server code!!

public class Server{

    static ServerSocket listen;

    static DataOutputStream dos;
    static DataInputStream dis;



    public static void main(String as[]){
         int data;
         try{
              listen = new ServerSocket(8888);
              Socket socket = listen.accept();
              dos = new DataOutputStream(socket.getOutputStream());
              //dis = new DataInputStream(socket.getInputStream());
              FileInputStream fis = new FileInputStream(new File("Server.java"));
              int count = 0;
         //     BufferedReader br = new BufferedReader(fr);
              while((data = fis.read()) != -1 ){
                         count++;
                   dos.write(data);
                         dos.flush();
              }
                    System.out.println( "Total number of char written : " + count );
              dos.close();
              fis.close();
         }
         catch(Exception e){
              System.out.println("error " + e);
         }
    }
}
0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6229633
Hi,

I revoke my long comment--after inspection of doc I found that write() has int parameter. But there is still conversion problem in server code: pw.print(data); will convert int to decimal string representation, while you need simply char with correspondent code to be written. Replacing print() by write() should solve the problem.

Oops. One more conversion problem: on client side you read byte from InputStream and write it as char to Writer. That at least unsafe--there is a big range of bytes which will be changed bu such operation.

Compare Viswa's suggestion to your code--it looks like (s)he did it right.

Regards,
Igor Bazarny
0
 

Author Comment

by:anitharamunni
ID: 6234168
Thanks viswa. The code works perfect now

0
 
LVL 1

Expert Comment

by:viswa081400
ID: 6234769
welcome!!
And thanx for the points
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java Message handling in Service Layer 3 57
micro services vs rest web services 16 84
Error with Java/Cache JDBC Classpath 2 30
VB Script to add site to Java Exception List 4 49
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now