2

I currently have a java program that requires quick communication between the client and server. I have decided to use UDP, after trying out TCP and RMI, which both were too slow for my purposes.

I have multiple ArrayLists that are stored in one ArrayList, which is then sent to the server. This method has worked fine in TCP and RMI, but it is required in UDP that this is changed to bytes.

ArrayList<Object> array = new ArrayList<Object>();
array.add(arrayList1);
array.add(arrayList2);
array.add(arrayList3);
array.add(arrayList4);
array.add(arrayList5);
array.add(arrayList6);

// Convert the ArrayList to bytes, then send to client

Each of the ArrayLists being added to the ArrayList that is being sent to the client contains objects and each ArrayList contains different types of objects. Most of the ArrayLists contain objects resulting from classes that I have created, but I do not think it is necessary to show them.

I have searched the internet for the answer to converting an ArrayList of ArrayLists to a byte, but the .getBytes() method does not work on the ArrayLists or the objects inside them.

If you need more examples of the code I am using, feel free to ask. The code above is not my real code(as numbering ArrayLists would be extremely confusing), but it is an accurate representation of what I am trying to achieve.

Thank you.

Anonymous
  • 179
  • 12
  • 1
    You could use [serialization](https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html), or convert your objects to a standard format such as JSON or XML. – Jesper Mar 15 '17 at 14:33
  • 1
    I think you have to use serialization for it. Could you check [article](http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array)? – Roma Khomyshyn Mar 15 '17 at 14:33
  • He's already doing serialization (byte array). Using JSON or XML (these 2 formats can be used only on http or higher protocols) can only slow things down. If TCP is not good enough for you, I don't htink UDP will help either (because it's basically TCP without security). I presume you're using Java sockets? – dsp_user Mar 15 '17 at 14:41
  • Also, you can't send an ArrayList over TCP either, so I don't think you used TCP to begin with. – dsp_user Mar 15 '17 at 14:47
  • Yes, it is possible to send an ArrayList over TCP, using ObjectOutputStream. – Anonymous Mar 15 '17 at 15:16

3 Answers3

2

To do it in UDP, it would be something like this:

In view of server:

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
    public static Object deserialize(byte[] data) throws IOException,   ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}
public static void main(String[] args) {
    new Server();
    byte[] receiveData = new byte[65536];
    byte[] sendData = new byte[65536];
    try (DatagramSocket datagramSocket = new DatagramSocket(3333);) {
        Board.start = true;
        while (true) {
            try {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                datagramSocket.receive(receivePacket);
                ArrayList<Object> object1 = (ArrayList)deserialize(receivePacket.getData());
                InetAddress address = receivePacket.getAddress();
                int port = receivePacket.getPort();
                ArrayList<Object> array = new ArrayList<Object>();
                array.add(arrayList1);
                array.add(arrayList2);
                array.add(arrayList3);
                array.add(arrayList4);
                array.add(arrayList5);
                array.add(arrayList6);
                sendData = serialize(array);
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
                datagramSocket.send(sendPacket);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }



        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

In view of client:

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}
public static void main(String[] args) {
    new Client();
    try {
        DatagramSocket clientSocket = new DatagramSocket();
        byte[] sendData = new byte[65536];
        byte[] receiveData = new byte[65536];

        while (true) {
            try {
                ArrayList<Object> fromUser = new ArrayList<Object>();
                fromUser.add(arrayList1);
                fromUser.add(arrayList2);
                sendData = serialize(fromUser);
                InetAddress address = InetAddress.getByName("localhost");
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, 3333);
                clientSocket.send(sendPacket);

                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                clientSocket.receive(receivePacket);
                ArrayList<Object> object = (ArrayList)deserialize(receivePacket.getData());
                arrayList1 = (ArrayList<Object>)object.get(0);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }   
        }
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
1

enter link description. Here it this your solution.

To RMI I did it like that

In the view of Client

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

public interface InterfaceUsuario extends Remote {   
  public ArrayList< User >getList() throws RemoteException;     
}

To get array data object: In the view of Client

InterfaceUser or;
        or = (InterfaceUser)Naming.lookup ("or");            
ArrayList listUser = or.getList();

In the view of Server

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

private Session sesion;
private Transaction tx;

public class UserDAO {

public ArrayList<User> getListUser() throws Exception {
ArrayList<User> listContacts = null;  

try 
{ 
    sesion = HibernateUtil.getSessionFactory().openSession();
    tx = sesion.beginTransaction();
    listContacts = (ArrayList<User>) sesion.createQuery("from   User").list();           


}finally 
{ 
    sesion.close(); 
}  

return listContacts; 
}
}
}
Community
  • 1
  • 1
ivan martinez
  • 186
  • 1
  • 8
1

I have found that this solution works for Java UDP using the serialization method,

public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException,   ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}

sending the ArrayList,

ArrayList<Object> array = new ArrayList<Object>();
array.add(arrayList1);
array.add(arrayList2);
array.add(arrayList3);
array.add(arrayList4);

sendData = serialize(array);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
datagramSocket.send(sendPacket);

and then receiving it.

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
ArrayList<Object> object = (ArrayList)deserialize(receivePacket.getData());
ArrayList<Object> arrayList = (ArrayList<Object>)object.get(0);

This seems to work for me, so I think that this method should work for you.