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.

Similar Messages

  • Sending command apdu with a byte array as CDATA

    Hi,
    I am learning java card as part of my final year project. So far I think I can do most of the basic things but I have got stuck at one particular point.
    I know that there are different constructors for creating a command apdu object and a number of these constructors take an array of bytes as CDATA values.
    My problem is, how to access this array of data in the card side because apdu.getBuffer() returns an array of integers (bytes)? And what is actually on apdu.getBuffer()[ISO7816.OFFSET_CDATA)] location when you send command apdu object using such a constuctor?
    regards
    Edited by: 992194 on 06-Mar-2013 06:12

    992194 wrote:
    (..) I should have mentioned earlier that my card use jc 2.2.1 version, and i have read from different places that this version does not support ExtendedLength facility.Indeed.
    Also I understand the semantics of apdu.getBuffer()[ISO7816.OFFSET_CDATA] that is the first byte of the command data. My question is, this command data was initially supplied as an array of bytes. Something like this:
    +new CommandAPDU(CLA, INS, P1, P2, DATA_ARRAY, Le)+
    So when you call:
    byte [] buffer = apdu.getBuffer()
    So does this mean that the byte values inside DATA_ARRAY automatically occupy locations +buffer[ISO7816.OFFSET_CDATA]+ onwards inside the buffer?Yes. The length would be<tt> (short)(buffer[ISO7816.OFFSET_LC]&0xFF) </tt>. Notice the<tt> &0xFF </tt> is a must above 127 bytes.
    Or their is a mechanism of extracting the DATA_ARRAY array itself?No.
    In fact, in the interest of performance and portability in environments with little memory, the usual coding style is to pass<tt> buffer </tt>, an offset within that, and the length; rather than making an object, which would require a copy. Welcome to the real world of Java Card.

  • HT5312 I have tried to send the email to reset my security questions for my iTunes account but the system will not send me the email with the link. How can I start recieving the email?

    My email is valid and I know this because I am receiving other email from Apple and this is the only email I have not been able to recieve. please help

    You need to ask Apple to reset your security questions; ways of contacting them include clicking here and picking a method for your country, phoning AppleCare and asking for the Account Security team, and filling out and submitting this form.
    (97764)

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

  • Firefox is trying to send strange multiple requests on port 7070. As I allow the request nothing appears in "http headers" addon window. What could this be?

    Hi.
    I discovered my Firefox v26 was SOMETIMES trying to send multiple requests on port 7070 (ukrainian ip-address) independently on what websites were opened at the moment.
    The problem remains after v27 update.
    I have an addon "live http headers" installed.
    As I manually allow the request by firewall nothing appears in the headers window.
    Does my firefox seem to be modified with adware/spyware?

    Have you tried Opening your Firefox in Safe Mode
    [[Troubleshoot Firefox issues using Safe Mode]]
    please report back to us

  • How to send different type of data

    Hello, everyone,
    I am trying to send different types of data between client and server.
    For example, from server to client, I need to send some String data, using PrintWriter.println(String n); and send some other stuff using OutputStream.write(byte[] b, int x, int y). What I did is setting up a socket, then send them one by one. But it didn't work.
    I am just wondering if there is anything I need to do right after I finished sending the String data and before I start sending other stuff using OutputStream. (Because if I only send one of them, then it works; but when I send them together, then the error always happened to the second one no matter I use PrintWriter first or the OutputStream first)

    To send mixed type of data by hand allways using the same output/input stream, you could do:
    on server side
            ServerSocket serverSocket = null;
            Socket clientSocket = null;
            OutputStream out = null;
            try
                /*setup a socket*/
                serverSocket = new ServerSocket(4444);
                clientSocket = clientSocket = serverSocket.accept();
                out = new BufferedOutputStream(clientSocket.getOutputStream());
                /*send a byte*/
                int send1 = 3;
                out.write(send1);
                /*send a string with a line termination*/
                String send2 = "a string sample";
                out.write(send2.getBytes("ISO-8859-1"));
                out.write('\n');
            finally
                try { out.close(); }
                catch (Exception e) {}
                try { clientSocket.close(); }
                catch (Exception e) {}
                try { serverSocket.close(); }
                catch (Exception e) {}
    on client side
            Socket clientSocket = null;
            InputStream in = null;
            try
                clientSocket = new Socket("localhost", 4444);
                in = new BufferedInputStream(clientSocket.getInputStream());
                /*receive the byte*/
                int receive1 = in.read();
                System.out.println("The received message #1 is: " + receive1);
                /*receive the string up to the line termination*/
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int c;
                while (((c = in.read()) != '\n') && (c != -1))
                    baos.write(c);
                String receive2 = baos.toString("ISO-8859-1");
                System.out.println("the received message #2 is: " + receive2);
            finally
                try { in.close(); }
                catch (Exception e) {}
                try { clientSocket.close(); }
                catch (Exception e) {}

  • Need to send and receive larger byte array

    I have a small WCF service, self hosted in a console app. On the same computer I have a client application. Both are running in the debugger in VS2008. The proxy code and the config file were generatred from the running service using svcutil.
    In one of the service calls, the service reads a pdf file and sends the contents as a byte array. The client receives the byte array, saves it as a pdf file, and displays it.
    Everything is fine for all other kinds of calls, and this one works fine also as long as the file is small (say 14K). But if the file is larger (say 84K), the client crashes (VHOST has stopped working).
    Is there some kind of setting that will allow me to send and receive larger byte arrays (> 100 K)?
    Thanks,
    Jon Jacobs
    In transmission, subatomic particles managed by professionals.
    No innocent electrons were harmed.

    Hi Jon,
    You'll want something like this to increase the message size quotas:
    <bindings>
    <basicHttpBinding>
    <binding name="basicHttp" allowCookies="true"
    maxReceivedMessageSize="20000000"
    maxBufferSize="20000000"
    maxBufferPoolSize="20000000">
    <readerQuotas maxDepth="32"
    maxArrayLength="200000000"
    maxStringContentLength="200000000"/>
    </binding>
    </basicHttpBinding>
    </bindings>
    The justification for the values is simple, they are sufficiently large to accommodate most messages. You can tune that number to fit your needs. The low default value is basically there to prevent DOS type attacks. Making it 20000000 would allow for a distributed
    DOS attack to be effective, the default size of 64k would require a very large number of clients to overpower most servers these days.
    If you're still getting this error message while using the WCF Test Client, it's because the client has a separate MaxBufferSize setting.
    To correct the issue:
    Right-Click on the Config File node at the bottom of the tree
    Select Edit with SvcConfigEditor
    A list of editable settings will appear, including MaxBufferSize.
    Note: Auto-generated proxy clients also set MaxBufferSize to 65536 by default.
    Let me know if this helped.
    Regards,
    Raghu

  • What's the best way to send multiple photo's to another iMac

    My friend has an iMac and they are trying to send multiple photo's to my iMac.  Can anyone let me know the best method to send them please.

    AdamTurner333 wrote:
    My friend has an iMac and they are trying to send multiple photo's to my iMac.  Can anyone let me know the best method to send them please.
    Unless these are very small photos or few in number they should use a sharing service, DropBox is good but there are many others.

  • Cannot send multiple photos via text on iPhone 6

    iPhone 6:  I am trying to send multiple pictures via text message (through the Photo app) to someone who does not have an Apple device, therefore I am sending it as an MMS.  However, I receive an error message stating, "iMessage needs to be enabled to send this message."  This is confusing for two reasons:
    1. I DO have iMessage enabled.
    2. I am not trying to send it via iMessage (as the recipient is a non-Apple user) so why am I being prompted to send it via iMessage?
    How do I fix this?

    What happens if you open a message and then copy multiple pictures into it (rather than doing it from the Photo app)?
    Thanks

  • How to use the JE database with other data types than byte arrays?

    Hi! I searched the javadoc of Berkley DB JE, for a way to introduce entry (but I need also retrieve) data with other type than byte arrays, e.g. String, or anything else, as int may be, etc.
    Still, I didn't find any such way, because the main (only?!) method to entry data into an open database - according what I found in javadoc - is:
    "public OperationStatus put(Transaction txn, DatabaseEntry key, DatabaseEntry data) throws DatabaseException"
    and both this and the corresponding method for retrieves, are based on the same DatabaseEntry type, which allow only entry data on byte[] support.
    What if I need to use Strings or int, or even char? I must do a special conversion from these types, to byte[], to use the database?
    Thank you!

    On the doc page (this is also in the download package),
    http://download.oracle.com/docs/cd/E17277_02/html/index.html
    see:
    Getting Started Guide
    Java Collections Tutorial
    Direct Persistence Layer (DPL)
    All of these describe how to use data types other than byte arrays.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to save a value in a byte array, retrieve it and display it?

    Hi,
    I am doing a project for my data structures class that involves saving a value (given in String format) in a byte array (our 'memory'). Initially I just tried casting character by character into the byte array and casting back to char[] for retrieval (using .toString() to return what's supposed to be the original string), but this did not work. I tried the .getBytes() method, applying it to the string and then trying to recover it by placing the contents of the 'memory' in a byte array and applying toString(), but that didn't work either. I looked a bit and found this class, CharsetEncoder and CharsetDecoder. I tried to use these but when I try the compiler tells me I cannot instantiate CharsetDecoder because it is an abstract class. At this point I'm at a loss as to what I can do. Is there any way to place a string in a byte array and then recover the string in it's original format? For example, I might save a value in my particular class of "456". But when I try to recover the value from my 'memory' i.e. the byte array, it comes out like [gnue@hnju.... or something similar. I need it to output the original string ("456").
    Below is my code as it is right now, for the methods setValue and getValue.
    Thanks!
    public void setValue(String value) throws InvalidValueException {
         //… stores the given value in the memory area assigned to the variable
              if(this.type.isValidValue(value)){
                   bytes = value.getBytes();
                   int i,j,k;
                   int l=0;//might be wrong?
                   int ad=address-(address%4);
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   if((address%4)+bytes.length-1<4){
                        for(i=address%4;i<address%4+bytes.length;i++)
                             reg.setByte(i, bytes[i]);
                        mem.setDataRegister(reg);
                        mem.writeWord(ad);
                   else if((address%4)+bytes.length-1>=4){
                        if(address%4!=0){
                             for(i=address%4;i<4;i++){
                                  reg.setByte(i, bytes);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        while(ad<address+bytes.length-(address+bytes.length)%4){
                             for(j=0;j<4;j++){
                                  reg.setByte(j, bytes[j+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        if((address+bytes.length)%4!=0){
                             mem.readWord(ad);
                             reg=mem.getDataRegister();
                             for(k=0;k<(address+bytes.length)%4;k++){
                                  reg.setByte(k, bytes[k+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                   else
                        throw new InvalidValueException("The value passed is not valid.");
         /** Gets the current value of the variable.
         @return current value converted to String
         public String getValue() {
              //… returns the current value stored in the corresponding memory area
              //… value is converted to String
              bytes=new byte[this.getType().getSize()];
              int i,j,k;
              int l=0;//might be wrong?
              int ad=address-(address%4);
              mem.readWord(ad);
              reg=mem.getDataRegister();
              if((address%4)+bytes.length-1<4){
                   for(i=address%4;i<address%4+bytes.length;i++)
                        bytes[i] = reg.readByte(i);
              else if((address%4)+bytes.length-1>=4){
                   if(address%4!=0){
                        for(i=address%4;i<4;i++){
                             bytes[i] = reg.readByte(i);
                             l++;
                        ad+=mem.WORDSIZE;
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   while(ad<address+bytes.length-(address+bytes.length)%4){
                        for(j=0;j<4;j++){
                             bytes[j+l] = reg.readByte(j);
                             l++;
                        ad+=mem.WORDSIZE;
                   if((address+bytes.length)%4!=0){
                        mem.readWord(ad);
                        reg=mem.getDataRegister();
                        for(k=0;k<(address+bytes.length)%4;k++){
                             bytes[k+l] = reg.readByte(k);
                             l++;
              return bytes.toString();

    You can certainly put it into a byte array and then construct a new String from that byte array. Just calling toString doesn't mean you'll automatically get a meaningful string out of it. Arrays do not override the toString method, so the use the one inherited from object.
    Look at String's constructors.

  • Not possible to store multiple fileReference object in same array?

    Hi all,
    I'm trying to store multiple fileReference  object in one array. But everytime I push() in a new object the old  objects that's already in the array gets set to the latest object.
    I'm  letting the user select an image. Then I push the selected  fileReference object into an array like my_array.push(  FileReference(event.target) );
    If I then run a loop on  "my_array" to check it's content I'm getting the latest pushed  fileReference object for every index in the array.
    With one object pushed in:
    1. Image1.jpg
    With two objects pushed in:
    1. Image2.jpg
    2. Image2.jpg
    Anyone have any thoughts on this?
    Thank you so much

    This is basically what I'm doing. The code is cut out from a larger portion so there might be errors, but hopefully not.
    // Local Files
    private var localFiles:FileReference           = new FileReference();
    private var fileList:Array                = new Array();
    private function browse(event:MouseEvent)
         trace("[Browse] Using local files");
         localFiles.addEventListener(Event.SELECT, onLocalFilesSelected);
         localFiles.browse(getAllowedTypes());
    * LOCAL FILE
    private function onLocalFilesSelected(e:Event)
         localFiles.addEventListener(Event.COMPLETE, localFileHandler);
         localFiles.load();
    private function localFileHandler(event:Event):void
         localFiles.removeEventListener(Event.COMPLETE, localFileHandler);
         fileList.push(FileReference(event.target));
         showFileList();
    private function showFileList():void
         for(var $x:int=0;$x<fileList.length;$x++)
              var file:FileReference = FileReference(fileList[$x]);
              trace($x+": " + file.name);
    Thank you

  • Convert float to 4 bytes array

    How can I convert float type to 4 byte array -
    not with strings but to exact binary representation.

    See the javadoc of Float.floatToIntBits. Converting an int to an array of 4 bytes is easy, so I will left it as an exercise.
    floatToIntBits
    public static int floatToIntBits(float value)Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout.
    Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number. Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent. Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.
    If the argument is positive infinity, the result is 0x7f800000.
    If the argument is negative infinity, the result is 0xff800000.
    If the argument is NaN, the result is 0x7fc00000.
    In all cases, the result is an integer that, when given to the intBitsToFloat(int) method, will produce a floating-point value the same as the argument to floatToIntBits (except all NaN values are collapsed to a single "canonical" NaN value).
    Parameters:
    value - a floating-point number.
    Returns:
    the bits that represent the floating-point number.

  • Imageicon created from byte array gives -1 height and -1 width...

    Hi,
    when I am trying to create an imageicon object from byte arrays the length and width of the object are coming to be -1.So I am unable to resize the image..
    This is happening for only few images, most of them are working fine and I can resize it...
    What possibly could be wrong??
    ImageIcon imageIcon = new ImageIcon(pImageData) where pImageData is bytearray..
    but I am getting imageIcon.getIconWidth()=-1
    and
    imageIcon.getIconHeight()=-1
    Can anyone help???

    es5f2000 wrote:
    I'm not sure if this is related, but I believe that images which are not currently being rendered return -1, -1 as their size.It is not even correct, so I'm confident it is not related.
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.imageio.ImageIO;
    import java.net.URL;
    class TestIconSize {
         public static void main(String[] args) throws Exception {
              Image image = ImageIO.read( new URL(
                   "http://forums.sun.com/im/silver-star.gif") );
              ImageIcon imageIcon = new ImageIcon( image );
              System.out.println( "Width: " + imageIcon.getIconWidth() );
              System.out.println( "Height: " + imageIcon.getIconHeight() );
    }Output.
    andrew@pc1:/media/disk/projects/numbered/all$ java TestIconSize
    Width: 16
    Height: 16
    andrew@pc1:/media/disk/projects/numbered/all$ The post after yours seems of even more dubious quality. For those (and other) reasons, I second Darryl's call for an SSCCE.

  • I have tried a lot to find an app or some way in email to attach multiple of pdf files in one email. I could not find anything that sends multiple pdf file in one email and still keeping the file in simple pdf format for the recipient.

    I have tried a lot to find an app or some way in email to attach multiple of pdf files in one email. I could not find anything that sends multiple pdf file in one email and still keeping the file in simple pdf format for the recipient.

    I am not aware of a way except for photos that allows you to select multiple files in an email. I even checked settings in the Adobe Reader app, and it does not show that ability.

Maybe you are looking for