如何将对象的ArrayList(ArrayLists)转换为字节数组?

时间:2017-03-15 14:30:30

标签: java arraylist udp byte

我目前有一个需要客户端和服务器之间快速通信的java程序。在尝试使用TCP和RMI之后,我决定使用UDP,这两者对我来说都太慢了。

我有多个存储在一个ArrayList中的ArrayLists,然后发送到服务器。这种方法在TCP和RMI中运行良好,但在UDP中需要将其更改为字节。

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

添加到发送到客户端的ArrayList的每个ArrayLists都包含对象,每个ArrayList包含不同类型的对象。大多数ArrayLists包含由我创建的类生成的对象,但我认为没有必要显示它们。

我在互联网上搜索了将ArrayLists的ArrayList转换为字节的答案,但.getBytes()方法对ArrayLists或其中的对象不起作用。

如果您需要更多我正在使用的代码示例,请随时提出。上面的代码不是我真正的代码(因为编号ArrayLists会非常混乱),但它准确地表示了我想要实现的目标。

谢谢。

3 个答案:

答案 0 :(得分:2)

要在UDP中执行此操作,它将是这样的:

鉴于服务器:

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();
    }
}

鉴于客户:

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 :(得分:1)

enter link description. 这是你的解决方案。

对于RMI,我这样做了

在客户视图

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;     
}

获取数组数据对象: 在客户视图中

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

在服务器视图

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; 
}
}
}

答案 2 :(得分:1)

我发现此解决方案适用于使用序列化方法的Java UDP,

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();
}

发送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);

然后接收它。

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);

这似乎对我有用,所以我认为这种方法适合你。