简体   繁体   English

使用asynctask从套接字返回对象

[英]return an object from socket using asynctask

I am trying to save a Collection which I get through a socket connection. 我正在尝试保存通过套接字连接获得的集合。 I use AsyncTask to read the message from socket that has the Collection. 我使用AsyncTask从具有Collection的套接字读取消息。 My problem is that I cannot save this message. 我的问题是我无法保存此消息。 In OnpostExecute() the Log.d() messages are not being displayed. OnpostExecute() ,不会显示Log.d()消息。 If I do ReceiveMsgAsyncTask().execute().get() the UI freezes. 如果我执行ReceiveMsgAsyncTask().execute().get()则UI冻结。 I have read many similar issues but I cannot find a solution. 我读过许多类似的问题,但找不到解决方案。 How can I save the message received from my socket?Thanks in advance.. 我该如何保存从套接字收到的消息?

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

Here is the Server's method that sends the Collection to client 这是将集合发送到客户端的服务器方法

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

I am guessing that your Worker class does not implement Serialializable 我猜你的Worker类没有实现Serialializable

See Javadoc 参见Javadoc

Only objects that support the java.io.Serializable interface can be written to streams. 只有支持java.io.Serializable接口的对象才能写入流。

please look at the document for AsyncTask.get() it clearly states 请查看文档中的AsyncTask.get(),其中明确指出

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

Therefore calling 'get' negates the whole reason to use an asynctask. 因此,调用“ get”会否决使用asynctask的全部原因。

What you need to do is: 您需要做的是:

  1. Create an interface with a call back method. 使用回调方法创建接口。
  2. make your activity or fragment implement that interface. 使您的活动或片段实现该接口。
  3. make your ReceiveMsgAsyncTask take an object implementing that interface on it's constructor. 使您的ReceiveMsgAsyncTask带有一个在其构造函数上实现该接口的对象。
  4. in the onPostExecute of ReceiveMsgAsyncTask call the callback method passing your results into it. 在ReceiveMsgAsyncTask的onPostExecute中,调用将结果传递给它的回调方法。

Now common pitfall here is what happens if the activity is closed or otherwise rendered defunct. 现在,这里常见的陷阱是,如果活动被关闭或以其他方式被取消,将会发生什么。 This can cause crashes and all kinds of other weirdness. 这可能会导致崩溃和其他各种怪异现象。

The easiest way to solve that issue is to keep copies of any outstanding asynctasks and cancel then in your activities or fragments onPause methods. 解决该问题的最简单方法是保留所有未完成的异步任务的副本,然后在活动或onPause方法的片段中取消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM