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

Similar Messages

  • InsufficientMemoryException while sending large byte array in WCF Service callback

    Hi
    I have a datacontract with a large byte array that is passed by the WCF Service back to the client using a callback contract.
    Until the byte array size remains below 25-30 MB, it is passed OK, but as soon as it exceeds that, an InsufficientMemoryException is thrown on the service side. I have set the max message sizes at 100 MB and using MTOM Encoder.
    I am using WSDualHTTPBinding with sessions and message security - hence streaming is not an option. I know chunking channels are an option, but I want to try to tune the service and client to maximize the byte array size which can be sent over a normal channel.
    Kindly advise how to tune settings to get to around 100 MB byte array size.
    Binding section of web.config is given below. Same settings for sizes are used on client.
    Thanks
    Abhishek
     <wsDualHttpBinding>
            <binding name="WSHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
    transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="100000000" maxReceivedMessageSize="100000000" messageEncoding="Mtom" textEncoding="utf-8" useDefaultWebProxy="true">
              <readerQuotas maxArrayLength="100000000"  />
              <security mode="Message">
                <message clientCredentialType="Certificate" algorithmSuite="Default"  />
              </security>
            </binding>
          </wsDualHttpBinding>

    Hi abhisinghal21,
    >>InsufficientMemoryException while sending large byte array in WCF Service callback
    First please try to increase the timeout value in the both client and service side to see if it works:
    closeTimeout="00:10:00" openTimeout="00:10:00"
    receiveTimeout="00:10:00" sendTimeout="00:10:00"
    Then since you do not want to the use the Chunking option to help you, maybe you try to change the wsDualHttpBinding to use the binding which supports the streaming mode and supports callback.
    In streaming transfer mode, the receiver can begin to process the message before it is completely delivered. And the streaming mode is useful when the information that is passed is lengthy and can be processed serially. Streaming mode is also useful when the
    message is too large to be entirely buffered. So it will be better for you to use the streamed mode.
    For more information, please try to check:
    #How to: Enable Streaming:
    http://msdn.microsoft.com/en-us/library/ms789010(v=vs.110).aspx .
    Best Regards,
    Amy Peng
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Sending a byte array of greater length than the APDU data buffer

    Hello again, I am now trying to send a byte array of length 480 from the smart card. I've tried setting the outgoing length to 480 first but as i had expected, this threw an exception. Then i tried setting it to 240 and then copying from the array into the apdu buffer in two halves and calling sendBytes() twice, but this only worked the first time - it send the first 240 bytes and then threw an error. Is it possible to do what i am trying to accomplish? If so, what am I missing?

    the applet:
    H:\java_card_kit-2_2_1-win-dom\java_card_kit-2_2_1\samples\src\com\sun\javacard\samples\photocard
    the client:
    H:\java_card_kit-2_2_1-win-dom\java_card_kit-2_2_1\samples\src_client\com\sun\javacard\clientsamples\photocardclient
    here is the code i have used to store large data on card. maybe it will help you.
    i send a series of apdu, where each contains 128 bytes of data (all apdu must have the same length - except the last).
    public void writeAPDU(APDU apdu)
         byte[] buffer = apdu.getBuffer();
         short lc = (short)(buffer[ISO7816.OFFSET_LC]&0xFF);          
         short p1 = (short)(buffer[ISO7816.OFFSET_P1]&0xFF); // counter
         short p2 = (short)(buffer[ISO7816.OFFSET_P2]&0xFF); // length of send data
         short offset = (short)(p1 * p2); // calculate the offset
         apdu.setIncomingAndReceive();
         // check for first apdu (contains the total size of data)
         if(p1 == 0 && p2 == 0)
              short l = Util.getShort(buffer,ISO7816.OFFSET_CDATA);
              data = new byte[l];
         else
              // store bytes in array
              Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, data, offset, lc);
    }

  • How send the u array through labview

    Hi,
    How to send the unsigned 32 bit  array through UDP.
    How to convert the unsigned 32 bit array to byte array.
    with regards and warm welcome,
    Ramamoorthy S
    Solved!
    Go to Solution.

    You can typecast it to a string and then typecast it back to a U32 array on the other end.
    You can also use flatten tro srring/unflatten from string.
    Have a look at the example finder for some examples.
    LabVIEW Champion . Do more with less code and in less time .

  • NetBeans MobilityPack 5 BUG?? how can I send a byte array?

    I�ve created a WebApp and a Simple servlet with one public method.
    public byte[] getStr(byte[] b) {       
    String s = "A string";
    return s.getBytes();
    Then I've used "Mobile To Web App" wizard to generate stubs to that getStr method. And when I�ve tried to call that getStr method:
    byte[] aByte = "st".getBytes();
    byte[] b = client.getStr(aByte);
    I've got an error at Server in Utility.java in generated ReadArray method.
    * Reads an array from the given data source and returns it.
    *@param source The source from which the data is extracted.
    *@return The array from the data source
    *@exception IOException If an error occured while reading the data.
    public static Object readArray(DataInput in) throws IOException {
    short type = in.readShort();
    int length = in.readInt();
    if (length == -1) {
    return null;
    } else {
    switch (type) {
    case BYTE_TYPE: {
    byte[] data = new byte[length];
    in.readFully(data);
    return data;
    default: {
    throw new IllegalArgumentException("Unsupported return type (" + type + ")");
    At this line "in.readFully(data);" I�ve got an EOFException.
    The the aByte = "st".getBytes(); was 2bytes long and at the server "int length = in.readInt();" it was 363273. Why?
    All code was generated by NetBeans Mobility pack 5 it's not mine so its a bug?
    How can I fix this?

    I found that bug. I've described it here
    http://www.netbeans.org/issues/show_bug.cgi?id=74109
    There's a solution how to fix the generated code.

  • Sending publickey through the network as a byte array.

    I send client public key form server to client as a byte array through the network. I'm sruggling when I get that byte array from client side and again assign to the PublicKey variable. Anyone can give me any hints how can I extract the public key from the byte array.
    Thank you

    If your public key is from an X509 certificate, you can use the X509EncodedKeySpec class.

  • 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 to send byte array of image with 300dpi.

    Hello fiends
                       i am making an application in which i have to send the byte array of an image with 300dpi.
    so i am using image snapshot class for that and use that code.
                        var snapshot:ImageSnapshot = ImageSnapshot.captureImage(cnvParent,300);
                        var bdata:String = ImageSnapshot.encodeImageAsBase64(snapshot);
    but when i send that bdata to php end using httpService.The size at other end of image increases surprisingly.i means it will increase its actual height and actual width.so is there any way to overcome this increase in size when i bitmapped image at 300 dpi?
    if there any way then please tell me.waiting for your reply.
    Thanks and Regards
        Vineet Osho

    Thanks david for such a quick reply.the link is really helpful.So we have to calculate the screendpi thruogh our code and then set the height and width of image.is there any simple way to sort out my problem.i just want to print my image at 300dpi but i am using image snapshot class so its taking the snap of my container(image) and save the image at 96 dpi which is dpi of my screen(monitor).so is there any way or any class in flex through which i got the image at its original dpi.i am not stick on 300 dpi but i m getting image from backend through xml at 300dpi.thats why i want the byte array i am sending should be at 300dpi.i am totally confused now.so please help me.
    Thanks and regards
      Vineet osho

  • Another question?? being able to send byte arrays containing multiple types

    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 rather just create one object and be able to send and receive the information on both ends
    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.

    which forum should I be posting this on?Serialization.
    To get you started...
    public class O_struct implements Serializable {                                                                                                                                                                                                                                                                                   

  • 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.

  • Sending byte array to server

    Does anyone know how to send a byte array to the server?

    What is contained in the byte array? Is it audio/video/image?
    If you can get a binary representation of it, you could probably
    convert it to Base64 and send it over as a string and reconvert to
    binary on the server.

  • 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

  • Byte array convert to image works fine for a peiod of time, Then error

    Hi all
    I'm on a program of reading incoming image set which comes as byte arrays through socket and convert them back to images using the method.
    javax.microedition.lcdui.Image.createImage();This works perfect for some time.
    But after 1 minute of running it gives an error
    java.lang.OutOfMemoryError: Java heap space
            at java.awt.image.BufferedImage.getRGB(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.loadImage(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.createImageFromData(Unknown Source)
            at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at com.sun.kvem.sublime.MethodExecution.process(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.processRequest(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.run(Unknown Source)My J2ME client code
    public class ChangeImage extends Thread
        private SocketConnection sock = null;
        private Image img = null;
        private CanvasKey canvas = null;
        private InputStream in = null;
        public ChangeImage(SocketConnection sock, Canvas canvas) throws IOException
            this.sock = sock;
            this.canvas = (CanvasKey) canvas;
            in = sock.openInputStream();
        public void run()
            super.run();
            short length;
            while (true)
                DataInputStream din = null;
                try
                    din = new DataInputStream(in);
                    length = din.readShort();     // to determine next data packet size
                    byte[] arr = new byte[length];  // next data packet store here
                    din.readFully(arr);  //read image
                    img = Image.createImage(arr, 0, arr.length);
                    canvas.setImage(img);
                    ChangeImage.sleep(50);
                catch (Exception ex)
                    ex.printStackTrace();
    }When I comment following line no error prints.
    img = Image.createImage(arr, 0, arr.length);So the problem is not with socket program.
    What is this problem? Think old image isn't being flushed!!! in the method javax.microedition.lcdui.Image.createImage();Please help me.

    Forgot to Mention i'm using Windows 8.1 - 32 GB Ram - i7-3970x - 2 SSd's in raid 0 for C Drive/ Storage drive is three ( 2 tb HDD in a raid 0 ) / Pictures Folder defaults to the Storage Drive not the Application drive .

  • How do I get a byte array from an object passed into the JNI?

    This is what my java code looks like:
    public class streamedData
    protected byte[] m_value = null;
    public byte[] getByteArray ()
    return m_value;
    /* code not pertaining to this question snipped. */
    jclass streamedDataClass = env->GetObjectClass(jstreamedData);
    // Get methodIDs for the various NPKI_Extension methods
    value = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
    lstreamedData->value = (unsigned char *)malloc (lstreamedData->length);
    if (lstreamedData->value == NULL)
    return INSUFFICIENT_MEMORY;
    memset (lstreamedData->value, 0, lstreamedData->length);
    memcpy (lstreamedData->value, env->CallByteMethodA(streamedDataClass, value, NULL), lstreamedData->length);
    This is not working.
    My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
    Any help would be appreciated. Why oh why can't there be a CallByteArrayMethod????

    My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
    You can retrieve a handle to the byte array, through a method call, as you're doing now, or by directly accessing it through GetFieldID.
    In the case of the method call, you'll want to do:jmethodID getByteArrayMethod = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
    jbyteArray byteArray = static_cast<jbyteArray>( env->CallObjectMethod( jstreamedData, getByteArrayMethod ) );In the case of field access, you can do:jfieldID m_valueFieldID = env->GetFieldID( streamedDataClass, "m_value", "[B" );
    jbyteArray byteArray = static_cast<jbyteArray>( env->GetObjectField( jstreamedData, m_valueFieldID ) );Once you have byteArray, you need to access it using the array operations:lstreamedData->value = env->GetByteArrayElements( byteArray, 0 );
    // Do what you want to do, then release the array
    env->ReleaseByteArrayElements( byteArray, lstreamedData->value, 0 );As always, Jace, http://jace.reyelts.com/jace, makes this easier. For example,void printByteArray( jobject jstreamedData ) {
      streamedData data( jstreamedData );
      JArray<JByte> byteArray = streamedData.m_value();
      for ( int i = 0; i < byteArray.length(); ++i ) {
        cout << byteArray[ i ];
    }God bless,
    -Toby Reyelts

  • How to read an inputStream in UTF-8 into a byte array.

    Hi, Java version is 1.4.2. If inputStream.read() is used to read the bytes into a byte array, is it guarenteed that UTF-8 chars are correctly transferred into byte array? Or should we use InputStreamReader? An example would be a great help.
    Thanks in advance.

    I would like to send a byte array read from InputStream to another app where they are converted to UTF-8. In brief
    -Read input stream which comes in UTF-8 into a byte array
    -Send byte array to another app which will convert it into UTF-8 characters

Maybe you are looking for

  • Abap engine

    Hey, Is there any ABAP engines available which can be downloaded from net. Rakesh.

  • XML validation problem

    hi, i am trying to validate an xml document against a schema document abnd am getting some strange validation errors. i am using xerces to parse. here are my java classes:- //---------------------------------------- class Validation------------------

  • HT4081 is original ipad compatible with ios6?

    Is the original ipad 1 compatible with ios6? or only supported up to ios5? I cannot restore current ipad 3 content to an old ipad.

  • How to get rid of background image when I scroll up or down in safari?

    Since I have downloaded OS Mavericks on my macbook pro I have a problems with Safari.  Whenever I scroll up or down on any webpage and ugly background of clipart looking images appears instead of the original grey background.   This is the best image

  • Cannot Update Any Adobe Apps, Patch Failed

    Hello, I'm having some major issues updating my apps. I've now uninstalled many times and reistalled many times. I've tried many suggestion with no luck.