gpt4 book ai didi

java - 在 AsyncTask 中通过套接字接收两个不同的数组

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:18 24 4
gpt4 key购买 nike

我有一个用于小型多人游戏的 Java 服务器。当关键字 update 到达时,我想通过连接的套接字向客户端发送两个不同的数组。

output.reset();
output.writeObject(array1);
output.writeObject(array2);

其中 array1 为 int[16],array2 为 int[2][2]

在 Android 客户端中,我有两个 AsyncTask 用于捕获数组。

@Override
protected int[] doInBackground(ObjectInputStream...params) {
ObjectInputStream ois = params[0];

try {
arrayFromServer = (int[]) (ois.readObject());
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return arrayFromServer;
}

@Override
protected int[][] doInBackground(ObjectInputStream... params) {
ObjectInputStream ois = params[0];

try {
complexArrayFromServer = (int[][]) (ois.readObject());
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return complexArrayFromServer;
}

我将它们传递给我的 UI Activity ,就像这样,使用计时器每 20 秒发送一次关键字更新

    public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 5000, 20000);
}

public void initializeTimerTask() {

timerTask = new TimerTask() {
public void run() {

handler.post(new Runnable() {
public void run() {

//AsyncTask
new CardTask() {

@Override
public void onPostExecute(int[] result) {
mFromServer = result;
}
}.execute(ois);

//AsyncTask
new PointsAndCardsTask() {

@Override
public void onPostExecute(int[][] result) {
mComplexArray = result;

}
}.execute(ois);
}
});
}
};
}

但这给我的游戏带来了一些问题,我很想知道我在发送数组时是否做错了什么,或者有更好的方法吗?

我收到的错误是

08-17 15:39:57.196: E/AndroidRuntime(665): FATAL EXCEPTION: main
08-17 15:39:57.196: E/AndroidRuntime(665): java.lang.ArrayIndexOutOfBoundsException

因为当我期待一个数组时,我得到了另一个数组。

最佳答案

我无法解释 Java 当(反)序列化此类数组时会发生什么,但我确信 Java 无法区分数组,因此您无法确保只获取具有所需维度的数组。

我会将您发送的数据封装在不同的 Java 对象中。通过这样做,您可以使用实例来确保您只得到您想要的!

关于java - 在 AsyncTask 中通过套接字接收两个不同的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32055671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com