Transferring primitive data types via UDP other than a String

Hi ALL,
I am new to Socket programming in UDP.
I need to implement a FTP client-server application.
Now the packet that I need to transfer using UDP as a DatagramPacket consists of multiple primitive data types, (3short types and 1 byte array of size 265.)
How do I do that?
All the samples and examples I managed to find on the Internet illustrated the problem of transferring a String type converted to getBytes and the byteArray is transferred.
However, in my case i need to pass this structure..(3fields) to the other side. If I convert the 4 fields to a single concatenated string there's this problem of finding out where each of the four fields begin and where do they end.
Please suggest and help...
thanks..
: )

Just create a class that represents your structure and convert-it to a byte array that can be sended over a DatagramSocket.
Try this sample code :
import java.io.*;
import java.net.*;
public class DP
    /** Creates a new instance of DP */
    public DP ()
     * @param args the command line arguments
    public static void main (String[] args)
        try
            System.out.println ("Starting server ...");
            DatagramServerThread server = new DatagramServerThread ("Datagram server");
            server.start ();
            System.out.println ("Creating your object ...");
            ByteArrayOutputStream baos = new ByteArrayOutputStream (); // Creating byte array output stream ..
            ObjectOutputStream oos = new ObjectOutputStream (baos);// Creating a object output stream that writes to byte array output stream..
            YourStructure newObject = new YourStructure (); // creating your data structure..
            newObject.setShortField1 ((short)12);// setting values ...
            newObject.setShortField2 ((short)45);
            newObject.setShortField3 ((short)4);
            newObject.setArray (new byte [256]);
            oos.writeObject (newObject); // write your structure to object output stream...
            byte data_to_be_sent[] = baos.toByteArray (); // retrieving equivalent byte array...
            // send data...
            DatagramSocket s = new DatagramSocket ();
            System.out.println ("Sending ...");
            DatagramPacket packet = new DatagramPacket (data_to_be_sent, data_to_be_sent.length);
            packet.setAddress (InetAddress.getByName ("localhost"));
            packet.setPort (8888);
            s.send (packet);
        catch (Exception e)
            e.printStackTrace ();
class YourStructure implements Serializable
     * Holds value of property shortField1.
    private short shortField1;
     * Holds value of property shortField2.
    private short shortField2;
     * Holds value of property shortField3.
    private short shortField3;
     * Holds value of property array.
    private byte[] array;
     * Getter for property shortField1.
     * @return Value of property shortField1.
    public short getShortField1 ()
        return this.shortField1;
     * Setter for property shortField1.
     * @param shortField1 New value of property shortField1.
    public void setShortField1 (short shortField1)
        this.shortField1 = shortField1;
     * Getter for property shortField2.
     * @return Value of property shortField2.
    public short getShortField2 ()
        return this.shortField2;
     * Setter for property shortField2.
     * @param shortField2 New value of property shortField2.
    public void setShortField2 (short shortField2)
        this.shortField2 = shortField2;
     * Getter for property shortField3.
     * @return Value of property shortField3.
    public short getShortField3 ()
        return this.shortField3;
     * Setter for property shortField3.
     * @param shortField3 New value of property shortField3.
    public void setShortField3 (short shortField3)
        this.shortField3 = shortField3;
     * Getter for property array.
     * @return Value of property array.
    public byte[] getArray ()
        return this.array;
     * Setter for property array.
     * @param array New value of property array.
    public void setArray (byte[] array)
        this.array = array;
    public String toString ()
        StringBuffer buffer = new StringBuffer ();
        buffer.append ("Short field 1 is ");
        buffer.append(this.getShortField1 ());
        buffer.append ("\nShort field 2 is ");
        buffer.append (this.getShortField2 ());
        buffer.append ("\nShort field 3 is ");
        buffer.append (this.getShortField3 ());
        buffer.append ("\nYour array field is ");
        for (int index = 0; index < this.getArray ().length; index++)
            buffer.append ("Index [" + index + "] = " + this.getArray () [index] + "\n");
        return buffer.toString ();
class DatagramServerThread extends Thread
    protected DatagramSocket socket = null;
    public DatagramServerThread (String name) throws IOException
        super (name);
        socket = new DatagramSocket (8888);
    public void run ()
        try
            byte buffer [] = new byte [socket.getReceiveBufferSize ()];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            System.out.println ("Server is ready. Waiting for packet ...");
            socket.receive(packet); // waiting for packet ...
            System.out.println ("Packet received! : ");
            byte received_data[] = packet.getData ();
            ByteArrayInputStream bais = new ByteArrayInputStream (received_data); // Creating byte array input stream ..
            ObjectInputStream ois = new ObjectInputStream (bais); // Creting Object input stream
            Object readed_object = ois.readObject ();
            YourStructure your_original_object = (YourStructure)readed_object;
            System.out.println (your_original_object.toString ());
            System.out.println ("Exiting server thread. Bye");
            socket.close ();
        catch (Exception e)
            System.err.println ("Server error");
            e.printStackTrace ();
}

Similar Messages

  • Creation of new primitive data types

    Is it possible to create primitive data types? Or perhaps there's another solution...
    I have a need to work with signed integers represented by more than 128 bits, and would prefer to define such variables as primitive types and be able to use them as such. I have no problem creating "toString()" and friends for convert binary to decimal.
    Thanks in advance.
    Randolf Richardson - [email protected]
    Inter-Corporate Computer & Network Services, Inc.
    Vancouver, British Columbia, Canada
    http://www.8x.ca/

    What about using "BigIntegers"?
    http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html

  • Primitive v/s Non-primitive data type

    Hi,
    I am new to java. What is the difference between primitive and non-primitive data type?

    hi Anand,
    there are hundred thousands of object in the Data Dictionary, so 15 won't harm much On the other hand, if you build up an ALV list based on this table, than it is good that you have these texts there with translations, etc.
    hope this helps
    ec

  • Runtime conversion of a string value to a primitive data type in java

    can anyone of you give me an idea to convert a string value to a primitive data type during run time...i have the value and the type to which it has to be converted as String values...do you have any idea ,...pls share

    String recvalvalue = inputval;
                    String recvartype = inputtype;
                   if (recvartype.equals("int")){
                   value0 = Integer.parseInt(recvalvalue);
             else
             if (recvartype.equals("double")){
                    value1  = Double.parseDouble(recvalvalue);
             else
             if(recvartype.equals("float")){
              value2 = Float.parseFloat(recvalvalue);
             else
             if(recvartype.equals("Boolean")){
              value3 = Boolean.parseBoolean(recvalvalue);
             else
             if(recvartype.equals("char")){
               value4 = (char)recvalvalue.charAt(0);
            else
            if(recvartype.equals("String")){
              value5 = recvalvalue;
             else
             if(recvartype.equals("byte")){
               value6 = Byte.parseByte(recvalvalue);
                  //listA.add(6, value6);
                  //     listA.g = value6;
             else
              if(recvartype.equals("long")){
               value7 = Long.parseLong(recvalvalue);
             else
              if(recvartype.equals("short")){
              value8 = Short.parseShort(recvalvalue);
             } yes i can do this but the resultant value has to be assigned to a variable of a specific type which is here recvartype .....it has to be done dynamically automatically..if we know what type of data is that we can convert and assign to the type but we donot know when we run the program as the program will be supllied by someone and has to be executed

  • JAX-RPC and non-primitive data types

    Hello all!
    I am using JWSDP v1.3 and i have a problem using non-primitive data types as return types for my operations.
    Consider the helloservice example of the JWSDP1.3 tutorial. Now suppose that instead of having the simple operation sayHello() that returns a String, we execute a query on a database, get some ResultSetMetaData and we want these Metadata to be the return type of our operation. I.e. have the operation
    public ResultSetMetaData sayHello()
    instead of the
    public String sayHello()
    of the tutorial.
    When trying to build the service i get the following error which is normal, because ResultSetMetaData is not a supported JAX-RPC type.
    run-wscompile: [echo] Running wscompile: [echo] C:\jwsdp\apache-ant\../jaxrpc/bin/wscompile.bat -define -d build - nd build -classpath build config-interface.xml -model build/model. gz [exec] error: invalid type for JAX-RPC structure: java.sql.ResultSetMetaData [exec] Result: 1
    Is there any way to define an operation like this? Can i specify somehow ResultSetMetaData as a supported-type?
    I hope someone can give me some advice on it, because i have lost one evening trying to figure it out myself :)
    Regards,
    Kostas

    Courtesy links to crossposts so people don't waste their time answering a question which has already been answered
    http://forum.java.sun.com/thread.jsp?thread=482875&forum=59&message=2253704
    http://forum.java.sun.com/thread.jsp?thread=482873&forum=331&message=2253699

  • Urgent!!!----Update a field of Long data type via trigger

    While it is obvious that it is no way for an Oracle trigger to update a field of a Long data type, is it a feasible way to call a java stored procedure from the trigger to achieve that purpose? If not, can you suggest any good solution to this?
    Thanks so much.

    Scripter -
    When you try to do a Set and Put, it is always good to explicitly set the statement's cursor type to something other than forward only, like keyset, and the lock type to something other than read-only. See if that helps...
    Scott Richardson
    National Instruments

  • Should Java introduce new primitive data types??

    In Java SE 5.0, many character- related methods (especially in the class Character) handle code points by using int type, i.e. return (code point) type is int, or receive (code point) int as parameter. This leads several problems. First, the variable used for storing returned result should be carefully stated, otherwise confusion may arise. Second, the parameters of method should be carefully ordered, otherwise conflict of method signature may meet.
    By those reasons, I suggest that Java should introduce new primitive data types for handling characters, they are:
    1. wchar
    this type states the variable stores 32-bit UNSIGNED integer, and it could be used to store either the code point, or the UTF-16 code of a character.
    2. ascii
    this type states the variable stores 8-bit UNSIGNED integer, and it could be used to store the code point of a elemental (ascii) character.

    short char, no. Nononono.
    No.
    wchar, I think I'd pref to see Java version 2 come
    out, and that be wchar by default, but that is not
    going to happen.
    I don't see a great need for it at this time.http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4504839
    Though I do not think that Java developer would like to change too much program code for using proposed (unsigned) primitive data types, I still believe that Java developer will eventually introduce these types, because it is not efficient to pretend signed integer to unsigned integer, and the success of a programming language is determined by how it can meet the programmers' need.

  • A newer version of data type BBP_PDS_HSS_IC was found than one required

    Hi,
    When I create a SC, it is automatically approved but the PO is not created.
    If I check TRX SM58 I get the message:
    "A newer version of data type BBP_PDS_HSS_IC was found than one required"
    Any ideas?
    Carlos Durazo

    Hi
    Which SRM version are you using ?
    By an chance have you created any new fields in the standard structure
    <b>'BBP_PDS_HSS_IC'</b> using <u>SE11</u> Transaction in SRM system. Please confirm the same by taking help of ABAP person here. Seems to be like the structure is not Activated completed. 
    <u>Related SAP OSS Notes -></u>
    Note 758067 - SRM 4.0: Change documents of new sets (DynAttr, Weight)
    Note 820201 - Document changes for attachments does not work
    Hinweis 691880 - Changes in tolerances not displayed in purchase order
    Note 1018714 - Change documents: Time stamp of the application server
    Note 1006898 - Deleted vendor not displayed in Change hist of Shopping cart
    Do let me know.
    Regards
    - Atul

  • Primitive data types as a sequence of bytes

    Does anyone have any experience of converting between primitive data types and sequences (i.e. arrays) of bytes? In particular I want to transmit primitive data types over a socket connection by writing a sequence of bytes.
    Thanks in advance.

    Yes. My personal favourite class for this is java.nio.ByteBuffer though you can also do it with java.io.DataInputStream/DataOutputStream and that might work better with sockets. ByteBuffer is particularly useful with pre-specified formats since you can specify big/little endian storage.

  • Setting precision to primitive data types

    How can I set precisions to the primitive data types, viz, double and float??
    I'm writing a program in which I've declared a double variable as follows :
    double d=12.00
    System.out.println(d);
    The output is 12.0 but I want it to be 12.00
    How can it be done??

    You have to use a BigDecimal:
            BigDecimal bd = new BigDecimal(12);
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            System.out.println(bd);

  • JAVA primitive data types - Signed/ unsigned etc.

    1. Are the following data types signed or unsigned in JAVA?
    byte, short, int, long, float, double
    2. I have tried using "Integer" in place of "int" and the program runs perfectly. Why is this so when "Integer" is not a reserved word in JAVA?
    Thanks.

    And to answer your first question, byte, short, int, long, float and double are all signed.
    As a part of the core of the language, Sun developed a series of 'collections' classes; Vector, ArrayList, etc. All of these classes, in the days before generics, were able to store instances of the Object class or anything that derived from it. Therefore, to store an int, a float or a double value into one of these collections classes, it was necessary to wrap it up in an instance of one of those classes that derived from Number. These are the wrapper classes that the previous poster alluded to. Typically, the wrapper class has a similar name to the primitive data type but with a capital latter; int - Integer, double - Double, etc.

  • How to invoke a class at run-time for primitive data types?

    Hi,
    I am trying to invoke classes at run-time.
    I am using Class.forName("className") for that where the "className" is also obtained at run-time .
    The problem I am getting is when the "className" is "int" or "char" etc. the call to Class.forName("int") etc. fails giving ClassNotFound error. It works fine for "className" is "java.lang.String" or "java.lang.Integer" etc.
    How can I correct this?
    thanks in advance-
    kg

    Hi,
    Thanks all for the valuable inputs.
    I have created a hashtable of primitive data types in the form of "int" as key and "Integer.TYPE" as the object in that element of the hashtable.
    Now there is another problem I am facing and that is of 'Casting at run-time'.
    Problem is there when the Database type is 'NUMBER' which returns me a "java.lang.BigDecimal" when I do a ResultSet.getObject("XXX") for that whereas the method in the javabean expects an "int" type.
    This causes "java.lang.IllegalArgumentException: argument type mismatch"
    So I want to cast it at runtime. How can I do it?
    Here is the code I am trying (which generates the above exception)
    public static void setBeanField(Class pCls,Object pObj,String pMethodName ,Object pColumnValue,Class
    pColumnTypeClass){
    try{
    if(pColumnValue!=null){
    Class[] paramTypes = new Class[]{pColumnTypeClass};
    Object[] args = new Object[]{pColumnValue};
    Method meth = pCls.getMethod(pMethodName,paramTypes);
    meth.invoke(pObj,args);
    }catch(Exception e){
    System.out.println("Exception in TestInrospection.setBeanField " + e);
    thanks in advance-
    kg

  • Is string primitive data type?

    - Is String a primitive date type? Elaborate please.
    - How is String object is mutable?

    > It is completely immutable. Once created it cannot be changed.
    import java.lang.reflect.*;
    public class ImmutableStringDemo {
        public static void main(String[] args) throws Exception {
            String string = "foo";
            System.out.println(string);
            new StringChanger().change(string);
            System.out.println(string);
    class StringChanger {
        public void change(String s) throws IllegalAccessException {
            Field[] fields = s.getClass().getDeclaredFields();
            for (Field f : fields) {
                f.setAccessible(true);
                if (f.getType() == char[].class) {
                    f.set(s, "bar".toCharArray());
    }QED. ;o)
    ~

  • In the attached VI why does one loop coerce the data type while the other doesn't?

    In the attached VI why does one loop coerce  the data type while the other doesn't?
    Solved!
    Go to Solution.
    Attachments:
    AAA.vi ‏8 KB

    I'm guessing you created the Enum on the front panel.  If you right-click it and create an indicator, it will match the type, and be an enum.  LabVIEW represents enums as U16, but because the types aren't identical (for example, your enum has 3 values, but a U16 has 65,536 values), LabVIEW automatically coerces (or converts) the smaller (enum) representation into the larger (U16) value.

  • Data type of the value in a string

    is it possible to determine what is the data type of the value of my string? for example if the user enters an integer, how do i know its an integer?

    if what the user entered is either 1 character,more than
    1 characters(a string), a whole number with no
    decimail places(an int) or a number with decimal
    places(a double).Those aren't mutually exclusive possibilities. If the user enters12345is that supposed to be a string with 5 characters or a whole number?
    how do i do that before i actually
    come to the Integer.parseInt or double.parsedouble
    statement?You don't. You use those statements to determine whether the string input can be interpreted as an integer or as a double.

Maybe you are looking for

  • Big problems. cant install windows xp

    Hello. I was playing BF2 as i did 200 hours on my HW, then i get a bluescreen. Cant load win again after this. Ive tried change the disk to a IDE disk, but same problem. I bougth a new mainboard(had 915p) 945p but still same problem. I changed cd-rom

  • Failover when delay of 1 day.

    Hi, my configuration is as that 4 node RAC 10.2.0.3 -> 2 node RAC physical standby with 1 day lag (no standby log max performance mode). After extensive studying Oracle doc I'm confused how to do failover in such scenario (delay in applying used). Sh

  • Pages crashes since Yosemite update

    I have two computers, a 15" MacBook Pro and a 11" Air. Since I updated to Yosemite, pages crashes overtime I try to use it. There are no other updates to fix this if it were a bug and all other programs are running perfectly. What can I do?

  • Printing not straight

    When I start to print the paper turns a little and the printing isn't straight. Sometimes the left upper corner of the paper is crumpled too. I did an on-line chat with HP and all the person said was to use HP paper and let them know if that didn't w

  • My 3000 C200 won't display anything on start up for over an hour

    I have had this unit for three years and when it is turned on It displays a message ' optimising image' but I still can't see anything for at least an hour. This occurred after an update was installed, have tried going back to restore points previous