Socket connection, byte array

I've got a problem with byte array. It needs to be initialized f.e.
byte[] data = new byte[100];However, I'm gonna read input stream to that array
is.read(data);and input stream might be longer than expected f.e. 1000 bytes.
What can I do to predict the length of byte[] or avoid NullPointerException
public void connect() throws IOException {SocketConnection client = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
client.setSocketOption(client.DELAY, 0);
client.setSocketOption(client.KEEPALIVE, 0);
InputStream is = client.openInputStream();
OutputStream os = client.openOutputStream();
os.write("some string".getBytes());
int c = 0;
byte[] data = new byte[100];
is.read(data);
while((c = is.read()) != -1) {
System.out.print((char)c);
is.close();
os.close();
client.close();
}

excellent thanks
for other users:
    public byte[] getBytes() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        SocketConnection client = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
        client.setSocketOption(client.DELAY, 0);
        client.setSocketOption(client.KEEPALIVE, 0);
        InputStream is = client.openInputStream();
        OutputStream os = client.openOutputStream();
        os.write("some string".getBytes());
        int c = 0;
        while((c = is.read()) != -1) {
            baos.write(c);
        is.close();
        os.close();
        client.close();
        return baos.toByteArray();
    }

Similar Messages

  • Binary Socket Connection Interruption? bytes lost?

    Hi,
    I am starting with a short introduction: I am currently working on a project, which involves a server application written in .NET (C#) and a flash gui app as client (standalone flash player 10 [code is written in Actionscript 3.0]). The server constantly sends bitmaps to the client (up to 30fps). The connection is established using binary sockets and data ist streamed to avoid socket open/close/reconnection problems.
    The bitmaps sent to the client are marked with begin- and end-tags. A length field was added as well, to optimise the following parsing process. The client buffers the received data up to the point where an end-tag is found. The client reassambles the bitmaps on the screen by parsing the current buffer. Parsing means looking for begin-tags and length fields and/or end-tags of pictures packages. The resulting bitmap data is copied into a byte array and will loaded into a movieclip using the flash.display.Loader class ( bytePictureLoader.loadBytes( byteArray ); ).
    Basically looks/works like this:
    [SERVER]--->[BEGIN-TAG][LENGTH][BITMAPDATA][END-TAG]-[BEGIN-TAG][LENGTH][BITMAPDATA][END-T AG]-...--->[CLIENT]
    While testing, I found out that in some cases the data stream becomes currupted, i.e. data is lost and/or the transmittion is incomplete.
    A good thing is that this error is reproducable.
    It seems that as soon as the Flash Application Window is dragged (moved on Windows Desktop) the stream lacks data.
    The same error occurs, if too much data is sent to the client. The results are performance problems, data loss and other strange effects. The more data is sent on the stream, the more data has to be parsed and the more data gets lost somehow. Sometimes this leads to a memory problem, because Begin- and End-Tags aren't transmitted correctly. In order to fix (counteract) that, I discard data as long as there is no Begin-tag found and the buffer is cleared when the size exceeds 1Mb.
    It works so far, but the application lacks performance and stability.
    I.e. If 20 bitmaps per second with 620x390px are sent to the client, the client only receives 16 to 17 bitmaps, if the application does nothing else.
    If 30 bitmaps per second with 620x390px are sent to the client, the client only receives about 20 to 21 bitmaps.
    I am wondering, if there is actually a better solution the solve this problem.
    I am guessing that using actuall video streams would be better, then sending one bitmap at a time in a byte stream.
    Is there a proper example on how to build a client app in flash to receive/parse a binary data stream??
    Does anyone else has recognized the lost-data problem or the interruption of streams?? And is there a solution to this problem?
    thanks a lot for your attention hope you can help me out here!
    cu
    Tobi

    Hi Hakan,
    thx, but this doesn't work. I think flash struggels with the amount of data to parse. I tested sending images twice, but now i receive only 9 to 12 bitmaps out of 25 bitmaps sent.
    Strange thing is, the problem only occurs if the flash player is maximised. As soon as I minimize the flash player window, the parsing works fine, but the image is not being loaded. Guess that's a performance feature of the flash player to not render actuall screen elements as long as the windows window of the flash player is not visible.

  • Sending a Byte array through a socket

    Can someone please tell me how i can send a Byte array from a client to a sever using sockets?
    Thanks
    Mark

    This tutorial should do the trick:
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Receiving it as a byte array via socket

    Yes, I could know the data end as read() returning -1 and the total byte-count value is in my hand then. But, however, if the byte-count value is N, I want those bytes in a single byte array of size N. What could be the standard, quickest and smartest way of getting the byte array on a socket peer?

    hiwa wrote:
    The readFully() method takes a byte array as an argument. The size of the array can't be decided as the total data size when we begin reading. We don't know it yet then.
    My method would be:
    LOOP(read -> out to a ByteArrayOutputStream) -> call ByteArrayOutputStream.toByteArray()
    However, if there is/are more smarter ones ...What problem are you actually trying to solve here?
    Here's a possible "solution" for you.
    Use a buffer. Then read the buffer and append the contents to a larger buffer. With code like this.
    private byte[] mergeBuffers(byte[] a, byte b[]){
      byte[] newBuffer = new byte[a.length+b.length];
      System.arraycopy(a,0,newBuffer,0,a.length);
      System.arraycopy(b,0,newBuffer,a.length,b.length);
      return newBuffer;
    }so during the read loop as the buffer fills up add the results of the current buffer to your "super"-buffer or whatever you want that has all the data.
    And then when you have finished reading trim the byte array to fit.

  • How to send byte array and String values to servlet from Swing application

    Hi all,
    I am new to swing, servlet, and socket connection.
    I have swing application to draw images and some input data. I dont know to send to server.
    byte[] buf = baos.toByteArray();
    URL servletURL = new URL("http://10.70.70.1:8080/servlet/SaveImage)
    URLConnection conn = servletURL.openConnection();
    conn.setDoOutput(true);
    BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
    out.write(buf&a=aaaa&b=bbbbb);
    out.flush();
    out.close();
    can I do like this. Strings are received in server side perfect. but i cant get byte array data. Please help me.
    Thanks in advance.

    <img src="myservlet">
    In your myservlet:
    response.setContentType("image/jpeg");
    then write your image date via ImageIO that uses response output stream.

  • How to find the last element of a byte array

    Dear all,
    I have a byte array with a max lenght of 1024*50 bytes. In that array I store the bytes read from a file. How can I find where the array ends (i.e. which is the last valid element of the byte array)?
    Thank you for your help.
    Best Regards,
    JIM

    I want to send files over TCP connection using BufferedOutputStreams and BufferedInputStreams. The first side (e.g. the client) sends a file (e.g mp3 file or jpeg image) to the server using the code
      public void sendFile(Socket s, String FileName) throws Exception
              BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());  
              BufferedInputStream in = new BufferedInputStream(new FileInputStream(FileName));
              int len = 0;
              while ( (len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
              in.close();
              out.flush();
            }(The client does not close the BufferedOutputStream out because other files will be sent afterwards)
    Then, the server receives the file using the code:
            public void receiveFile(Socket s, String FileName) throws Exception
              OutputStream out = new BufferedOutputStream(new FileOutputStream(FileName)); 
              InputStream in = new BufferedInputStream(s.getInputStream());
              int len = 0;
              while ( (len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                break;
              out.flush();
              out.close();
            }(likewise the InputStream in is not closed for the same reasons).
    In order the server to receive the file and stop reading the BufferedInputStream, I will have to make some modifications to this part of the code,
    while ( (len = in.read(buffer)) > 0)so as to know when the whole file has been received.
    Thus, even if I send the length of each file, I will not be able to read it. Could you please recommend me a solution?

  • UnmarshalException for large byte array :: Weblogic 8.1 SP2

    Hi,
    1) We have a application running on Weblogic 8.1SP2.
    2) Our scenario consist of Client code which reads a input file via Stream and converts it to a byte array before sending it to the Server.
    When the server side code calls the Remote Bean (with byte array as an argument) it throws this exception :
    "java.rmi.UnmarshalException: Software caused connection abort: socket write error"
    Intermittently also got this error :: "weblogic.rjvm.PeerGoneException: ; nested exception is: java.io.EOFException"
    3) This scenario works absolutely fine if the said Input File is of a smaller size.
    4) I have also set the following params in config.xml <server .../> tag, but all in vain:
         CompleteMessageTimeout="480" also tried with "0"
         MaxMessageSize="2000000000"
         NativeIOEnabled="true"
    Also tried with :
         MaxHTTPMessageSize="2000000000" & MaxT3MessageSize="2000000000"
    Below is the exception trace:
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:297)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:244)
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:284)
         ... 6 more
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at java.net.SocketOutputStream.socketWrite0(Native Method)
         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
         at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
         at weblogic.socket.SocketMuxer.write(SocketMuxer.java:721)
         at weblogic.rjvm.t3.T3JVMConnection.sendMsg(T3JVMConnection.java:723)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendOutMsg(MsgAbbrevJVMConnection.java:276)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendMsg(MsgAbbrevJVMConnection.java:164)
         at weblogic.rjvm.ConnectionManager.sendMsg(ConnectionManager.java:549)
         at weblogic.rjvm.RJVMImpl.send(RJVMImpl.java:722)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSendRaw(MsgAbbrevOutputStream.java:292)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSend(MsgAbbrevOutputStream.java:300)
         at weblogic.rjvm.MsgAbbrevOutputStream.sendRecv(MsgAbbrevOutputStream.java:322)
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:103)
         ... 7 more
    Any thoughts would be helpful?
    Thanks,
    Khyati

    Hi,
    1) We have a application running on Weblogic 8.1SP2.
    2) Our scenario consist of Client code which reads a input file via Stream and converts it to a byte array before sending it to the Server.
    When the server side code calls the Remote Bean (with byte array as an argument) it throws this exception :
    "java.rmi.UnmarshalException: Software caused connection abort: socket write error"
    Intermittently also got this error :: "weblogic.rjvm.PeerGoneException: ; nested exception is: java.io.EOFException"
    3) This scenario works absolutely fine if the said Input File is of a smaller size.
    4) I have also set the following params in config.xml <server .../> tag, but all in vain:
         CompleteMessageTimeout="480" also tried with "0"
         MaxMessageSize="2000000000"
         NativeIOEnabled="true"
    Also tried with :
         MaxHTTPMessageSize="2000000000" & MaxT3MessageSize="2000000000"
    Below is the exception trace:
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:297)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:244)
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:284)
         ... 6 more
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at java.net.SocketOutputStream.socketWrite0(Native Method)
         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
         at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
         at weblogic.socket.SocketMuxer.write(SocketMuxer.java:721)
         at weblogic.rjvm.t3.T3JVMConnection.sendMsg(T3JVMConnection.java:723)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendOutMsg(MsgAbbrevJVMConnection.java:276)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendMsg(MsgAbbrevJVMConnection.java:164)
         at weblogic.rjvm.ConnectionManager.sendMsg(ConnectionManager.java:549)
         at weblogic.rjvm.RJVMImpl.send(RJVMImpl.java:722)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSendRaw(MsgAbbrevOutputStream.java:292)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSend(MsgAbbrevOutputStream.java:300)
         at weblogic.rjvm.MsgAbbrevOutputStream.sendRecv(MsgAbbrevOutputStream.java:322)
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:103)
         ... 7 more
    Any thoughts would be helpful?
    Thanks,
    Khyati

  • Concatenate byte arrays

    I have a Socket that is sending data accross a connection. I want to keep reading more data into an array. Is there a way to add more data into an array, or do I have to create a new one every time.
    I'd like to do something like this:
    byte[] b = new byte[10];
    istrm.read( b2);
    b += b2; <----- I know this doesn't work
    I have been writing it like this:
    InputStream istrm = sock.getInputStream();
    byte[] b = new byte[ istrm.available()];
    istrtrm.read( b);
    but I don't know if that gets all of the data. If it blocks for a while, does that mean more data will come down the stream? I just want to make sure the data all gets there and put into 1 byte array.
    Thanks in advance.

    You cannot alter the size of an array object. You must allocate another array and copy the contents from the original. A better way would probably be to have a list of arrays, keeping track of the total received. THen create a single array and copy the data from the smaller arrays. You could have this happen whenever the list length exceeds a chosen boundary to avoid having too many small array objects referenced in memory.
    eg
    byte[] b1 = new byte[100];
    byte[] b2 = new byte[50];
    List list = new LinkedList();
    int totalSize = 0;
    list.add(b1);
    totalSize += b1.length();
    list.add(b2);
    totalSize += b2.length();
    byte[] b = new byte[totalSize];
    int currentPos = 0;
    for(Iterator iterator = list.iterator(); iterator.hasNext(); )
    byte[] temp = (byte[]) iterator.next();
    for(int count = 0; count < temp.length; count++)
    b[currentPos++] = temp[count];
    or something like that... (untested)
    Hope that helps...
    Talden

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • Trying to send multiple types in a byte array -- questions?

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but instead be able to stuff all 4 types into a byte array and then send it and correctly be able to retrieve all the info on the receiver's side.
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    public class O_struct implements Serializable {
    // writing
    ObjectOutputStream oos = ...;
    O_struct struct = ...;
    oos.writeObject(struct);
    // reading
    ObjectInputStream ois = ...;
    O_struct struct = (O_struct)ois.readObject();
    I will be sending 1000s of these byte arrays, and I'm sure having to create a new Double or Float on both ends will hinder this.
    I am worried that having to create new objs every time it is sending a byte array will affect my application.
    That's the wrong way to approach this. You're talking about adding complexity to your code and fuglifying it because you think it might improve performance. But you don't know if it will, or by how much, or even if it needs to be improved.
    Personally, I'd guess that the I/O will have a much bigger affect on performance than object creation (which, contrary to popular belief, is generally quite fast now: http://www-128.ibm.com/developerworks/java/library/j-jtp01274.html)
    If you think object creation is going to be a problem, then before you go and cock up your real code to work around it, create some tests that measure how fast it is one way vs. the other. Then only use the cock-up if the normal, easier to write and maintain way is too slow AND the cock-up is significantly faster.

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

  • How to add 16 bit message sequential number to the byte array

    hi
    iam trying to implement socket programming over UDP. Iam writing for the server side now.I need to send an image file from server to a client via a gateway so basically ive to do hand-shaking with the gateway first and then ive to send image data in a sequence of small messages with a payload of 1 KB.The data message should also include a header of 16 bit sequential number and a bit to indicate end of file.
    Iam able to complete registration process(Iam not sure yet).I dnt know how to include sequential number and a bit to indicate end of file.
    I would like to have your valuable ideas about how to proceed further
    package udp;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Sender  {
        protected BufferedReader in = null;
        protected FileInputStream image=null;
        protected static boolean end_of_file=true;
    /** pass arguments hostname,port,filename
    * @param args
    * @throws IOException
       public static void main(String[] args) throws IOException{
            DatagramSocket socket = new DatagramSocket(Integer.parseInt(args[1]));
            boolean more_messages = true;
              String str1=null;
                * gateway registration
                try{
                     //send string to emulator
                    String str="%%%GatewayRegistration SENDER test delay 10 drop 0 dupl 0 bandwidth 1000000";
                    byte[] buff=str.getBytes();
                    InetAddress emulator_address = InetAddress.getByName(args[0]);
                    DatagramPacket packet = new DatagramPacket(buff, buff.length,emulator_address,Integer.parseInt(args[0]));
                    socket.send(packet);
                        // figure out response
                    byte[] buf = new byte[1024];
                    DatagramPacket recpack=new DatagramPacket(buf,buf.length);
                    socket.receive(recpack);
                   // socket.setSoTimeout(10000);
                    String str2=str1.valueOf(new String(recpack.getData()));
                    if(socket.equals(null))
                         System.out.println("no acknowledgement from the emulator");
                        socket.close();
                    else if(str2=="%%%GatewayConfirmation")
                    //     String str1=null;
                         System.out.println("rec message"+str2);
                    else
                         System.out.println("not a valid message from emulator");
                         socket.close();
                catch (IOException e) {
                    e.printStackTrace();
                      end_of_file = false;
         /**create a packet with a payload of 1     KB and header of 16 bit sequential number and a bit to indicate end of file
      while(end_of_file!=false)
          String ack="y";
          String seqnum=
           File file = new File(args[2]);                               
                    InputStream is = new FileInputStream(file);                 
            socket.close();
      private byte[] byteArray(InputStream in) throws IOException {
             byte[] readBytes = new byte[1024]; // make a byte array with a length equal to the number of bytes in the stream
          try{
             in.read(readBytes);  // dump all the bytes in the stream into the array
            catch(IOException e)
                 e.printStackTrace();
            return readBytes;
      

    HI Rolf.k.
    Thank you for the small program it was helpfull.
    You got right about that proberly there  will be conflict with some spurios data, I can already detect that when writing the data to a spreadsheet file.
    I writes the data in such a way, that in each line there will be a date, a timestamp, a tab and a timestamp at the end. That means two columns.
    When i set given samplerate up, that controls the rate of the data outflow from the device, (1,56 Hz - 200 Hz),   the data file that i write to , looks unorderet.
     i get more than one timestamp and severel datavalues in every line and so on down the spreadsheet file.
    Now the question is: Could it be that the function that writes the data to the file,  can't handle the speed of the dataflow in such a way that the time stamp cant follow with the data flowspeed. so i'm trying to set the timestamp to be  with fractions of the seconds by adding the unit (<digit>) in the timestamp icon but its not working. Meaby when i take the fractions off a second within the timestamp i can get every timestamp with its right data value. Am i in deeb water or what do You mean!??
    AAttached Pics part of program and a logfile over data written to file
    regards
    Zamzam
    HFZ
    Attachments:
    DataFlowWR.JPG ‏159 KB
    Datalogfile.JPG ‏386 KB

  • Playing a wav file (byte array) using JMF

    Hi,
    I want to play a wav file in form of a byte array using JMF. I have 2 classes, MyDataSource and MyPullBufferStream. MyDataSource class is inherited from PullStreamDataSource, and MyPullBufferStream is derived from PullBufferStream. When I run the following piece of code, I got an error saying "EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7c9108b2, pid=3800, tid=1111". Any idea what might be the problem? Thanks.
    File file = new File(filename);
    byte[] data = FileUtils.readFileToByteArray(file);
    MyDataSource ds = new MyDataSource(data);
    ds.connect();
    try
        player = Manager.createPlayer(ds);
    catch (NoPlayerException e)
        e.printStackTrace();
    if (player != null)
         this.filename = filename;
         JMFrame jmframe = new JMFrame(player, filename);
        desktop.add(jmframe);
    import java.io.IOException;
    import javax.media.Time;
    import javax.media.protocol.PullBufferDataSource;
    import javax.media.protocol.PullBufferStream;
    public class MyDataSource extends PullBufferDataSource
        protected Object[] controls = new Object[0];
        protected boolean started = false;
        protected String contentType = "raw";
        protected boolean connected = false;
        protected Time duration = DURATION_UNKNOWN;
        protected PullBufferStream[] streams = null;
        protected PullBufferStream stream = null;
        protected final byte[] data;
        public MyDataSource(final byte[] data)
            this.data = data;
        public String getContentType()
            if (!connected)
                System.err.println("Error: DataSource not connected");
                return null;
            return contentType;
        public void connect() throws IOException
            if (connected)
                return;
            stream = new MyPullBufferStream(data);
            streams = new MyPullBufferStream[1];
            streams[0] = this.stream;
            connected = true;
        public void disconnect()
            try
                if (started)
                    stop();
            catch (IOException e)
            connected = false;
        public void start() throws IOException
            // we need to throw error if connect() has not been called
            if (!connected)
                throw new java.lang.Error(
                        "DataSource must be connected before it can be started");
            if (started)
                return;
            started = true;
        public void stop() throws IOException
            if (!connected || !started)
                return;
            started = false;
        public Object[] getControls()
            return controls;
        public Object getControl(String controlType)
            try
                Class cls = Class.forName(controlType);
                Object cs[] = getControls();
                for (int i = 0; i < cs.length; i++)
                    if (cls.isInstance(cs))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Time getDuration()
    return duration;
    public PullBufferStream[] getStreams()
    if (streams == null)
    streams = new MyPullBufferStream[1];
    stream = streams[0] = new MyPullBufferStream(data);
    return streams;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.media.Buffer;
    import javax.media.Control;
    import javax.media.Format;
    import javax.media.format.AudioFormat;
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.PullBufferStream;
    public class MyPullBufferStream implements PullBufferStream
    private static final int BLOCK_SIZE = 500;
    protected final ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW);
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM_MS, 8000.0, 8, 1,
    Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
    Format.byteArray);
    private int seqNo = 0;
    private final byte[] data;
    private final ByteArrayInputStream bais;
    protected Control[] controls = new Control[0];
    public MyPullBufferStream(final byte[] data)
    this.data = data;
    bais = new ByteArrayInputStream(data);
    public Format getFormat()
    return audioFormat;
    public void read(Buffer buffer) throws IOException
    synchronized (this)
    Object outdata = buffer.getData();
    if (outdata == null || !(outdata.getClass() == Format.byteArray)
    || ((byte[]) outdata).length < BLOCK_SIZE)
    outdata = new byte[BLOCK_SIZE];
    buffer.setData(outdata);
    byte[] data = (byte[])buffer.getData();
    int bytes = bais.read(data);
    buffer.setData(data);
    buffer.setFormat(audioFormat);
    buffer.setTimeStamp(System.currentTimeMillis());
    buffer.setSequenceNumber(seqNo);
    buffer.setLength(BLOCK_SIZE);
    buffer.setFlags(0);
    buffer.setHeader(null);
    seqNo++;
    public boolean willReadBlock()
    return bais.available() > 0;
    public boolean endOfStream()
    return willReadBlock();
    public ContentDescriptor getContentDescriptor()
    return cd;
    public long getContentLength()
    return (long)data.length;
    public Object getControl(String controlType)
    try
    Class cls = Class.forName(controlType);
    Object cs[] = getControls();
    for (int i = 0; i < cs.length; i++)
    if (cls.isInstance(cs[i]))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Object[] getControls()
    return controls;

    Here's some additional information. After making the following changes to MyPullBufferStream class, I can play a wav file with gsm-ms encoding with one issue: the wav file is played many times faster.
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM, 8000.0, 8, 1,
                Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
                Format.byteArray);
    // put the entire byte array into the buffer in one shot instead of
    // giving a portion of it multiple times
    public void read(Buffer buffer) throws IOException
            synchronized (this)
                Object outdata = buffer.getData();
                if (outdata == null || !(outdata.getClass() == Format.byteArray)
                        || ((byte[]) outdata).length < BLOCK_SIZE)
                    outdata = new byte[BLOCK_SIZE];
                    buffer.setData(outdata);
                buffer.setLength(this.data.length);
                buffer.setOffset(0);
                buffer.setFormat(audioFormat);
                buffer.setData(this.data);
                seqNo++;
        }

  • How to open a byte array of pdf into acrobat reader dynamically..

    hi,
    my java program is connecting to a url and downloading various file(.pdf,.xml format) into hard-disk. now the requirement is if user select "Preview" button, then file is downloaded and opened with appropriate application(acrobat reader for .pdf file) but not saved anywhere in hard-disk ...
    any idea, any hint any help is welcomed..
    thanks in advance..

    hi friends,
    i got the solution. i am using one external api of adobe acrobat, through which i am able to stream pdf document in form of byte array into acrobat viewer,without writing data in any file.
    so my work is done.. :)

Maybe you are looking for

  • CUCM 8.6.2 and AD LDAP SYNC

    We have an issue where we can loging and sync all users but then we can not log in as those users.  We are trying to reserach whether this is related to the LDAP user rights, firewall, etc.  Any ideas?  Thanks!

  • Problem with 400mm L 5.6 clarity

    On image tests my 400mm L 5.6 is performing significantly less sharp than my new 100-400mm lense. The only think I can think of that would have damaged the 400 was condensaton in the body from temperature changes. Shots are all tribod and cable trigg

  • Need API Name for PIck Release and Ship Confirm for WMS Module

    Hi All, One if my requirement is that Initially I will create Internal Sales Order and send to the other system (legacy) there they do the shipping then they provide the flat file which contains shipping information. Based on the incoming file I will

  • HT201210 iPhone freezing during restore.....

    My iPhone 4 keeps freezing about 60% way through a restore, according to iTunes when the firmware is being updated. Any ideas how to fix? I have tried a different computer, disabling my security software etc. and still no luck :o( (Windows)

  • Skype Click to Call - plugin is unresponsive - ANN...

    Why do I repeatedly see the message Plug-in Unresponsive The following plug-in is unresponsive: Skype Click to Call Would you like to stop it? Yes No