使用asynctask从套接字返回一个对象

时间:2014-01-22 01:00:26

标签: java android sockets android-asynctask

我正在尝试保存通过套接字连接获得的Collection。我使用AsyncTask从具有Collection的套接字读取消息。我的问题是我无法保存此消息。在OnpostExecute()中,未显示Log.d()消息。如果我ReceiveMsgAsyncTask().execute().get(),用户界面会冻结。我已经阅读了许多类似的问题,但我找不到解决方案。如何保存从套接字收到的消息?提前感谢..

private class ReceiveMsgAsyncTask extends AsyncTask<Object, Void, Object> {
    final Collection <String> col = new ArrayList<String>();
    Socket socket = null ;
    ObjectInputStream in = null;
    @Override
    protected Object doInBackground(Object... arg0) {
        // TODO Auto-generated method stub;
        Object msg = null;
         try {
                socket = new Socket(host,50000);
                in = new ObjectInputStream(socket.getInputStream());
                msg = in.readObject();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                try {
                    in.close();
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        return msg;
    }

    protected void onPostExecute(Object result) {
        // TODO Auto-generated method stub
        Log.d("mesg","success");
        super.onPostExecute(result);
        col.addAll((Collection<?extends String>)result);
    }

以下是将集合发送到客户端的服务器方法

public void splitData(Master master,String client){
        int chunk=0;
        int chunckStart=0;
            BufferedReader br = null;
            ObjectOutputStream out = null;
            try {
                String sCurrentLine;
                br = new BufferedReader(new FileReader("input"));
                int numberOflines=0;
                while ((sCurrentLine = br.readLine()) != null) {
                    numberOflines++;
                }
                br.close();
                br = new BufferedReader(new FileReader("input"));
                for (int i=1;i<=master.numberOfWorkers;i++){
                    out = new ObjectOutputStream(incoming.getOutputStream());
                    Worker Mworker = new Worker(clientsList.get(i-1));
                    if (i==master.numberOfWorkers){
                        if (numberOflines%master.numberOfWorkers!=0)
                            chunk = ((numberOflines/master.numberOfWorkers)*i)+numberOflines%master.numberOfWorkers;
                        else chunk = ((numberOflines/master.numberOfWorkers)*i);
                    }
                    else chunk = ((numberOflines/master.numberOfWorkers)*i);
                    int counter = chunk;
                    while (counter>chunckStart) {
                        sCurrentLine = br.readLine();
                        System.out.println(sCurrentLine);
                        //Mworker.reduce(sCurrentLine, 1);
                        Mworker.getCollection().add(sCurrentLine);
                        counter--;
                    }
                    System.out.println("----------------------------------");
                    chunckStart = chunckStart +(numberOflines/master.numberOfWorkers);
                    System.out.println(Mworker.getWorkerName()+" has the list:");
                    //System.out.println(Mworker.getHashReduce());
                    System.out.println(Mworker.getCollection());
                    out.writeObject(Mworker.getCollection());//send chunk to the worker/client
                    //out.flush();
                    //out.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null) br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            //Mworker.hashReduce
        //}
    }

2 个答案:

答案 0 :(得分:0)

我猜你的Worker类没有实现Serialializable

请参阅Javadoc

  

只有支持java.io.Serializable接口的对象才能写入流。

答案 1 :(得分:0)

请查看AsyncTask.get()明确说明

的文件

Waits if necessary for the computation to complete, and then retrieves its result.

因此,调用'get'会否定使用asynctask的全部理由。

您需要做的是:

  1. 使用回调方法创建界面。
  2. 使您的活动或片段实现该界面。
  3. 使您的ReceiveMsgAsyncTask获取在其构造函数上实现该接口的对象。
  4. 在ReceiveMsgAsyncTask的onPostExecute中调用将结果传递给它的回调方法。
  5. 现在常见的陷阱是,如果活动被关闭或以其他方式解散,会发生什么。这可能会导致崩溃和各种其他奇怪现象。

    解决该问题的最简单方法是保留任何未完成的asynctasks的副本,然后在您的活动或片段onPause方法中取消。