如何:通过套接字发送对象集合?

时间:2021-08-28 16:49:04

Suppose I want to send a collection of objects over a network via a socket in Java. For concreteness, suppose I want to send an array of BigInteger objects. The sender should simply send this array in one chunk over the socket, so that the receiver could cast the received object to the proper form.

假设我想通过Java中的套接字通过网络发送一组对象。具体来说,假设我想发送一个BigInteger对象数组。发送方应该简单地将这个数组发送到套接字上的一个块中,以便接收方可以将接收到的对象转换为正确的形式。

How can this be accomplished ?

如何实现这一目标?

I've tried using ObjectOutputStream to send this array of objects. However, it doesn't go as planned.

我已经尝试使用ObjectOutputStream来发送这个对象数组。但是,它没有按计划进行。

Some of the code:

一些代码:

        BigInteger[] bigIntegers = new BigInteger[10];
        bigIntegers[0] = new BigInteger("0");
        bigIntegers[1] = new BigInteger("1");
        outputStream = new ObjectOutputStream(socket.getOutputStream());
        outputStream.writeObject(bigIntegers);

I assume that the underlying architecture is the same at both ends.

我假设两端的底层架构是相同的。

Can someone show how to send such a collection of objects, as well as receive this collection on the other side of the socket?

有人可以展示如何发送这样的对象集合,以及在套接字的另一端接收此集合吗?

Thanks,

1 个解决方案

#1


you can send objects to server socket using

您可以使用将对象发送到服务器套接字

objectOut.writeObject(bigIntegers);
objectOut.flush();

and can retrieve that object at server side using here client is clientsocket

并且可以在服务器端检索该对象,这里客户端是clientsocket

ObjectInputStream objectIn = new ObjectInputStream(client.getInputStream());
BigInteger[] array = (BigInteger[]) objectIn.readObject();

#1


you can send objects to server socket using

您可以使用将对象发送到服务器套接字

objectOut.writeObject(bigIntegers);
objectOut.flush();

and can retrieve that object at server side using here client is clientsocket

并且可以在服务器端检索该对象,这里客户端是clientsocket

ObjectInputStream objectIn = new ObjectInputStream(client.getInputStream());
BigInteger[] array = (BigInteger[]) objectIn.readObject();