我想通过套接字向DataOutputStream发送一个点数组(Point points [] = new point [20]),并且能够在另一端使用DataInputStream正确读取它。我不能单独发送每个元素,它必须作为整个数组发送,并且能够被解释为整个数组。
答案 0 :(得分:1)
参见例如Advanced Socket Programming中的“传输自定义对象”部分:
无论如何,我也会考虑使用RMI。例如,您可以创建一个PointServer,在RMI注册表中注册它,并通过客户端应用程序中的简单函数调用来访问它。 RMI比套接字更容易使用。例如,您不必设计协议,只需要为分布式对象定义方法。
答案 1 :(得分:0)
为什么不使用ObjectInputStream / ObjectOutputStream?
这是我很久以前写过的一段代码,它允许你通过电线发送任何类型的对象,只要它是可序列化的,显然:
ObjectInputStream input = new ObjectInputStream(communicationSocket.getInputStream());
if (input != null) {
try {
Object o = input.readObject();
if (o != null && o instanceof DataObject) {
DataObject response = (DataObject) o;
{
//Do something cool with DataObject
}
}
}//etc...
DataObject
只是一个“包装器”/自定义类,您可以将其定义为具有Point []的其中一个属性;换句话说,您可以将DataObject定义为:
import java.io.Serializable;
public class DataObject implements Serializable {
private Point[] points; //etc - define getter setter for points
}
你可以把它写成:
output = new ObjectOutputStream(communicationSocket
.getOutputStream());
output.writeObject(yourDataObject);
现在,您可以这样阅读:
while (listening) {
try {
Object currentObject = input.readObject();
if (currentObject != null
&& currentObject instanceof DataObject) {
Point[] points = ((DataObject) currentObject).getPoints();
//Do something with points
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally {
listening = false;
}
}
答案 2 :(得分:0)
那么,您应该注意一些要点,例如,int 32或64位的大小,发送和接收机器的字节顺序等。 此外,应该有一个协议来传递两个套接字,我的意思是,每个数据包发送应该有一个标头,以便你知道你将收到多少数据,我不会处理,我认为你想要发送和接收20点的数组。 在这个例子中,假设两台机器都是32位,即int的大小是4字节,并且两台机器都使用LITTLE_ENDIAN字节顺序。
// To send an array of points use these two methods:
public byte[] pointsToBytes(Point[] p, int numPts)
{
// 2 is for x and y and 4 is the size of an int in bytes
ByteBuffer buff = ByteBuffer.allocateDirect(numPts * 2 * 4);
buff.order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < numPts; i++)
{
buff.putInt(p[i].x);
buff.putInt(p[i].y);
}
return buff.array();
}
public boolean sendData(Point[] pts, int size)
{
try
{
byte[] buffer = pointsToBytes(pts, size);
mainSocket.getOutputStream().write(buffer, 0, buffer.length);
return true;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
// To receive an array of point use these two methods:
public Point[] bytesToPoints(byte[] byteBuff, int numBytes)
{
ByteBuffer buff = ByteBuffer.wrap(byteBuff);
buff.order(ByteOrder.LITTLE_ENDIAN);
// 2 is for x and y and 4 is the size of an int in bytes
int ptsInBuffer = numBytes / 2 / 4;
Point[] pts = new Point[ptsInBuffer];
for (int i = 0; i < ptsInBuffer; i++)
{
pts[i].x=buff.getInt();
pts[i].y=buff.getInt();
}
return pts;
}
public Point[] getData(int pointsToRead)
{
try
{
byte[] buffer = new byte[pointsToRead * 4 * 2];
int bytesRead = mainSocket.getInputStream().read(buffer, 0, pointsToRead*4*2);
return bytesToPoints(buffer, bytesRead);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}