[英]Read and write from a socket simultaneously
I'm writing an android app in java and I want to create a listener that receive messages in a while(true)
loop, and also to be able to send messages to the server. 我正在用Java编写一个android应用,我想创建一个监听器,它可以在
while(true)
循环中接收消息,并且还能够将消息发送到服务器。 For this task I'm using sockets with asyncTask
. 对于此任务,我使用带有
asyncTask
套接字。 I have written a connectionHandler
class which handle all the send and receive requests for my app. 我编写了一个
connectionHandler
类,该类处理我的应用程序的所有发送和接收请求。
So far so good, everything is working fluently for just sending and receiving messages one at a time, but I just couldn't find a way to do it simultaneously. 到目前为止,一切都很顺利,一次只能发送和接收一条消息,但我只是找不到一种同时完成消息的方法。
I need to execute the following code in a thread, but I don't know how to do it, because I have to return a String
: 我需要在线程中执行以下代码,但是我不知道该怎么做,因为我必须返回
String
:
public static String receive() {
try {
return mConnectionHandler.new AsyncReceiveFromServer().execute()
.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
private class AsyncReceiveFromServer extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String result = null;
try {
result = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
When I'm running the receive function in a while(true)
loop, I can't send messages, because the ...execute().get()
is blocking the java class connectionHandler
. 当我在
while(true)
循环中运行receive函数while(true)
,我无法发送消息,因为...execute().get()
阻塞了Java类connectionHandler
。
So to sum up, how can I execute the above code in a thread or any other asynchronous way? 因此,总而言之,我如何以线程或任何其他异步方式执行以上代码? Or maybe you have any other suggestion to run the send and receive simultaneously while the receive is a
while(true)
loop? 或者,也许您还有其他建议在接收是
while(true)
循环的同时运行发送和接收?
First off- never use execute.get(). 首先,永远不要使用execute.get()。 If you think you need to use it, you're architected wrong- it breaks the entire point of using a thread to have the calling thread wait for a result.
如果您认为需要使用它,那么您就构造错了-它破坏了使用线程让调用线程等待结果的全部目的。 If you just call execute, you'll run on another thread and work fine.
如果仅调用execute,则将在另一个线程上运行并正常工作。 If you need more than 1 thread running truly simultaneously, use executeOnExecutor() to override the 4.0 shared thread pool mechanism of AsyncTask.
如果需要多个同时真正运行的线程,请使用executeOnExecutor()重写AsyncTask的4.0共享线程池机制。
Or better yet- don't use AsyncTask for this. 或更妙的是-不要为此使用AsyncTask。 You have something you want to run forever, waiting for input from a remote connection.
您想永久运行某些东西,等待来自远程连接的输入。 This is a better fit for a Thread than an AsyncTask.
这比AsyncTask更适合Thread。 I'd go with a thread and have the while loop built into the thread, and have the thread terminate only when the connection is closed.
我会选择一个线程,并在该线程中构建while循环,并让该线程仅在连接关闭时终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.