[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Sending byteArray between server and client

Posted on 2005-04-19
15
Medium Priority
?
401 Views
Last Modified: 2010-03-31
Hi All,

Here are snips of server and client that I need help to clarify the send and receive of a byteArray

Thanks in advance for your help.

Delphi3


Snip of Server

     
         byte[] bytes = byteArray.toByteArray(); // correctly gathered.

   
        ObjectOutputStream out=new  ObjectOutputStream(socket.getOutputStream());
       
        while ((true)&&(b<1))
        {
     
          out.writeObject(Integer.toString(bytes.length));// correctly sent

          out.writeObject(bytes);   <<<<  questionable format ???
          out.flush();
          //out.close();
          ++ b;
        }
        //closing the in & out streams
        in.close();//<<<<<<<<<<<
        out.close();//<<<<<<<<<<<
        socket.close();//<<<<<<<<<<





Snip of client


 public void getDataRequest ()throws IOException {
    while ((true) && (b<1))
    {
      if(getDataRequest) {
        try {
         int len;
          len =  Integer.parseInt((String)(inOIS.readObject()));  // correctly received.
         System.out.println(len);
          byte[] bytes = byteArray.toByteArray();

          bytes = Integer.parseInt((String)(inOIS.readObject())); <<<<<<<<<< questionable format???  
        }
        catch (Exception e) {
          System.out.println("error getting data");
        }
        ++b;
0
Comment
Question by:delphi3
  • 7
  • 4
  • 4
15 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 13818243
You don't need ObjectXput for byte arrays - any stream can send them
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 200 total points
ID: 13818260
If you want to send the length of the array first, don't send it as a String - that's not efficient. You can use a DataOutputStream

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeInt(bytes.length);
out.write(bytes);
out.close();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13818269
To receive

DataInputStream in = new DataInputStream(socket.getInputStream());
int length = in.readInt();
byte[] data = new byte[length];
in.readFully(data);
in.close();
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 86

Expert Comment

by:CEHJ
ID: 13818282
(Although you needn't send the length - you could just read to EOF and write into a ByteArrayOuputStream)
0
 
LVL 15

Assisted Solution

by:aozarov
aozarov earned 200 total points
ID: 13818573
If you want to send the full array then when you use ObjectOutputStream you don't need to write the array length.
You can just write the array and then receive the array in the other side.

server: out.writeObject(bytes);  

client byte[] bytes = (byte[]) in.readObject();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13819684
>>then when you use ObjectOutputStream

... but of course it's not efficient to send a byte array over an OOS unless you're using it to send objects (not arrays of primitives) too
0
 
LVL 4

Author Comment

by:delphi3
ID: 13820664
Point level increase
0
 
LVL 4

Author Comment

by:delphi3
ID: 13820668
Hi
I have decided to raise the point level so that each of you get 50 points.
This is not cleaned up, but in all its bad style, it is what I have been trying to get to happen for what
seems like months. I thank you both to respond and help me out.

Delphi3

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class localHostServerIOshoImage extends JFrame
{  
  private JTextField textConnection;
  private JLabel labelConnection;
  Container container = null;
  int b = 0;
  ByteArrayOutputStream byteArray = new ByteArrayOutputStream();// applied globally
 
  public localHostServerIOshoImage()    
  {    
    container = getContentPane() ;
    container.setLayout(new FlowLayout());
   
    labelConnection = new JLabel("Connection ") ;
    container.add(labelConnection );
    textConnection = new JTextField(15) ;
    container.add(textConnection);
    textConnection.setText("Disconnected");
   
    setSize (200,200) ;
    setVisible(true);
    try {
      InputStream is = new BufferedInputStream(new FileInputStream("NadiaFace.jpg"));      
      int n = 0;
      while (-1!=(n=is.read()))
      {
        byteArray.write(n);
       
      }
      byteArray.close();
      is.close();
     
      byte[] bytes = byteArray.toByteArray();      
      //creating server socket binding at port # 4000
      ServerSocket server=new ServerSocket(4000);
      System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":4000");
      System.out.println("Run the Client");
      //ready to accept client request
      while (true){//<<<<<<<<<<<
        b = 0; //>>>>>>>>> Delph3 added this
        Socket socket=server.accept();
        textConnection.cut();
        textConnection.setText("Connected\n");
       
       
        //opening the input stream to read data from client connection
        BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(in.readLine());
        //using output stream responsing data
        ObjectOutputStream out=new  ObjectOutputStream(socket.getOutputStream());
       
        while ((true)&&(b<1))
        {      
          out.writeObject(bytes);  
          ++ b;
        }
        //closing the in & out streams
        in.close();//<<<<<<<<<<<
        out.close();//<<<<<<<<<<<
        socket.close();//<<<<<<<<<<
      }//end while true//<<<<<<<<<<<    
    }
    catch(Exception err)
    {
      System.err.println("* err"+err);
      textConnection.cut();
      textConnection.setText("Disconnected\n");
    }
  }  
  public static void main(String a[])
  {
    new localHostServerIOshoImage();
  }  
}









import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class localHostServerIOshoImage extends JFrame
{  
  private JTextField textConnection;
  private JLabel labelConnection;
  Container container = null;
  int b = 0;
  ByteArrayOutputStream byteArray = new ByteArrayOutputStream();// applied globally
 
  public localHostServerIOshoImage()    
  {    
    container = getContentPane() ;
    container.setLayout(new FlowLayout());
   
    labelConnection = new JLabel("Connection ") ;
    container.add(labelConnection );
    textConnection = new JTextField(15) ;
    container.add(textConnection);
    textConnection.setText("Disconnected");
   
    setSize (200,200) ;
    setVisible(true);
    try {
      InputStream is = new BufferedInputStream(new FileInputStream("NadiaFace.jpg"));      
      int n = 0;
      while (-1!=(n=is.read()))
      {
        byteArray.write(n);
       
      }
      byteArray.close();
      is.close();
     
      byte[] bytes = byteArray.toByteArray();      
      //creating server socket binding at port # 4000
      ServerSocket server=new ServerSocket(4000);
      System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":4000");
      System.out.println("Run the Client");
      //ready to accept client request
      while (true){//<<<<<<<<<<<
        b = 0; //>>>>>>>>> Delph3 added this
        Socket socket=server.accept();
        textConnection.cut();
        textConnection.setText("Connected\n");
       
       
        //opening the input stream to read data from client connection
        BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(in.readLine());
        //using output stream responsing data
        ObjectOutputStream out=new  ObjectOutputStream(socket.getOutputStream());
       
        while ((true)&&(b<1))
        {      
          out.writeObject(bytes);  
          ++ b;
        }
        //closing the in & out streams
        in.close();//<<<<<<<<<<<
        out.close();//<<<<<<<<<<<
        socket.close();//<<<<<<<<<<
      }//end while true//<<<<<<<<<<<    
    }
    catch(Exception err)
    {
      System.err.println("* err"+err);
      textConnection.cut();
      textConnection.setText("Disconnected\n");
    }
  }  
  public static void main(String a[])
  {
    new localHostServerIOshoImage();
  }  
}
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13820754
Not sure what kind of feedback you are looking but I can provide the following:
1. why do you do this:
while ((true)&&(b<1))
        {      
          out.writeObject(bytes);  
          ++ b;
        }

instead of
out.writeObject(bytes); // after all true is true and b starts as zero

2. though you run this part only once I would change
    InputStream is = new BufferedInputStream(new FileInputStream("NadiaFace.jpg"));      
      int n = 0;
      while (-1!=(n=is.read()))
      {
        byteArray.write(n);
       
      }
      byteArray.close();
      is.close();
to
      InputStream is = new FileInputStream("NadiaFace.jpg");      
      byte[] bytes = new byte[1024];
      int n = 0;
      while (-1!=(n=is.read(bytes)))
      {
        byteArray.write(bytes, 0, n);        
      }
      byteArray.close();
      is.close();
3. move socket.close();//<<<<<<<<<<
   to a finally close (afer the catch Exception part)
4. This is the first time I see code that uses ObjectOutputStream with a different type of InputStream (and not ObjectInputStream), though this may work for you I recommend you to avoid it. The Object streams have several caveats that one needs to be aware of (e.g. the sequence of opening the streams)...
0
 
LVL 4

Author Comment

by:delphi3
ID: 13820956
aozarov,

I was looking for a soltion  of this format  from you in an earlier Q  from me.  Nothing came from the help that you gave me. Nothing that I could modify to give me a solution of this sort.

It took another Q post by me  to get this

 int n = 0;
      while (-1!=(n=is.read()))
      {
        byteArray.write(n);
      }
      byteArray.close();
     
    } catch (IOException e) {
    }
   


In the past  I have used Borland Delphi  ICS Webserver running on my desktop to test URL localhost downloads image/text downloading  and watched the text/image come directly from the appropriate server folder.  In Java I have had to to change the images to bytes, or Vectors madeup from  pixels colors.  

I wanted to try do this without downloading additional packages  other than the standard  j2sdk1.4.2_08.

Sure, to make this run above, requires two instances of Java IDE running, one for the server and the other for the client,   and it seems to take a lot of resources to make it happen, a pile of time to get it all running, and tends  to overload the system,  especially when anything else is running.

This is a bit of the why:  Just to see if it was possible.  And it is.
Not very pretty,  Would not buy  a cup of java at the corner  "Starbucks cafe".

D3









0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13822172
:-)

A bit more on this

>>while ((true)&&(b<1))

ahem... strange bit of code from a language point of view.

The second expression in the while clause will never be executed, so it's equivalent to:

while (true)

If you *did* want it to be evaluated then it would be

while ((true)&(b<1))

but then, of course, the first expression would be redundant
0
 
LVL 4

Author Comment

by:delphi3
ID: 13823451
CEHJ and  aozarov

Since both of you are questioning  that matter of ( b<1) it came  from my Q at EE about six months ago. Here is the reference and here is my final comment at  that Q.  Really, like I said this attempt  above is not a  picture programming  perfection.

I will take your remarks here and try to incorporate them by further testing and refinement.

D3

http://oldlook.experts-exchange.com:8080/Programming/Programming_Languages/Java/Q_21185748.html


I add this line to what revisions you have written.  
while (true){//<<<<<<<<<<<
       b = 0;//>>>>>>>>> Delph3 added this
        Socket socket=server.accept();

Running the client repeatedly now makes  versions of the image while the server running. It now works great in my estimation!

For those interested here is the completed, revised code as far as I want to take it with this Q.

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

// use applicPxlgrabMTstoBytes.java to make ColorPixlData.txt

public class localHostServerImage extends JFrame
{  
  private JTextField textConnection;
 private JLabel labelConnection;
 Container container = null;
 Vector vec1;
 Vector vec2;
 int b = 0;
 
 
 public localHostServerImage()    
 {    
   container = getContentPane() ;
   container.setLayout(new FlowLayout());
   
   labelConnection = new JLabel("Connection ") ;
   container.add(labelConnection );
   textConnection = new JTextField(15) ;
   container.add(textConnection);
   textConnection.setText("Disconnected");
   
   setSize ( 200,400) ;
   setVisible(true);
   try {
     FileInputStream fin = new FileInputStream("ColorPixlData.txt");
     ObjectInputStream inOStrm = new ObjectInputStream(fin);
     //image dimensions
     vec1 = (Vector) inOStrm.readObject();
     //image pixlColors
     vec2 = (Vector) inOStrm.readObject();
     inOStrm.close();
     
     //creating server socket binding at port # 3000
     ServerSocket server=new ServerSocket(3000);
     System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":3000");
     System.out.println("Run the Client");
     //ready to accept client request
     while (true){//<<<<<<<<<<<
       b = 0; //>>>>>>>>> Delph3 added this
        Socket socket=server.accept();
       textConnection.cut();
       textConnection.setText("Connected\n");
       
       
       //opening the input stream to read data from client connection
       BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
       System.out.println(in.readLine());
       //using output stream responsing data
       ObjectOutputStream out=new  ObjectOutputStream(socket.getOutputStream());
       
       while ((true)&&(b<1))
       {
         out.writeObject(vec1);
         //System.out.println(vec1);
         out.writeObject(vec2);
          //System.out.println(vec2);
         out.flush();
         //out.close();
         ++ b;
       }
       //closing the in & out streams
       in.close();//<<<<<<<<<<<
       out.close();//<<<<<<<<<<<
       socket.close();//<<<<<<<<<<
     }//end while true//<<<<<<<<<<<    
   }
   catch(Exception err)
   {
     System.err.println("* err"+err);
     textConnection.cut();
     textConnection.setText("Disconnected\n");
   }
  }
 
 public static void main(String a[])
 {
   new localHostServerImage();
 }  
}  
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13823676
>> while ((true)&&(b<1)) ... The second expression in the while clause will never be executed, so it's equivalent to: while (true)
Actually it is equivalent to  while (b < 1) ( and in his case starts as 0 so it will be executed one).
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13823715
>>Actually it is equivalent to  while (b < 1) ( and in his case starts as 0 so it will be executed one).

Yes you're right - it was rather early when i wrote that - for some reason i was reading it as ||
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13823991
I knew that ;-)
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month20 days, 2 hours left to enroll

873 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