有一种方法可以连接到套接字并发送消息并休眠一秒钟来处理响应。
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.websocket.WebSocket;
import com.ning.http.client.websocket.WebSocketTextListener;
import com.ning.http.client.websocket.WebSocketUpgradeHandler;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class SocketClient implements WebSocketTextListener {
private static org.slf4j.Logger log = LoggerFactory.getLogger(SocketClient.class);
private WebSocket websocket;
private List<String> serverResponse = new ArrayList<String>();
private List<String> logFromResponse = new ArrayList<String>();
public List<String> getAllLogs(String receiverId){
logFromResponse = new ArrayList<String>();
JSONObject jObj = new JSONObject();
try {
jObj.put("deviceId", receiverId);
}catch(Exception e){
log.warn("JSON Exception: "+e.getLocalizedMessage(), e);
}
connectToSocket();
if (websocket!=null)
websocket.sendTextMessage(jObj.toString());
responseFromServer();
return logFromResponse;
}
public boolean clearForDevice(String receiverId){
JSONObject jObj = new JSONObject();
try {
jObj.put("deviceId", receiverId);
}catch(Exception e){
log.warn("JSON Exception: "+e.getLocalizedMessage(), e);
}
connectToSocket();
if (websocket!=null)
websocket.sendTextMessage(jObj.toString());
String res = responseFromServer();
return (res!=null) && res.contains("Success");
}
private void connectToSocket() {
AsyncHttpClient c = new AsyncHttpClient();
AsyncHttpClient.BoundRequestBuilder builder = c.prepareGet(createUri())
.addHeader(HttpHeaders.Names.CONNECTION, "Upgrade")
.addHeader(HttpHeaders.Names.UPGRADE, "WebSocket");
websocket = builder.execute(new WebSocketUpgradeHandler.Builder()
.addWebSocketListener(this).build()).get();
}
@Override
public void onOpen(WebSocket webSocket) {
log.debug("Opening WebSocket");
}
@Override
public void onClose(WebSocket webSocket) {
log.debug("Closing WebSocket");
}
@Override
public void onError(Throwable throwable) { }
@Override
public void onMessage(String message) {
serverResponse.add(message);
}
@Override
public void onFragment(String s, boolean b) { }
private String responseFromServer() {
String response = null;
sleep(100);
if (!serverResponse.isEmpty()) {
//format message and send response and add to logFromResponse
}
return response;
}
protected void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
log.warn("Interrupted Exception: "+e.getLocalizedMessage(), e);
}
}
}
但是,我想在没有sleep()的情况下进行1秒,使用不阻塞io的AsyncHttpClient连接到套接字。我想创建一个可以发送消息并等待服务器响应的线程?我确实尝试通过实现runnable接口创建一个类,但没有运气! 有关如何创建对websockets的同步调用或阻止IO的任何建议。
UPDATE:使用synchronized块等待,然后在收到消息后通知!关注@Antoniossss评论
答案 0 :(得分:1)
直接来自宁主页
import com.ning.http.client.*;
import java.util.concurrent.Future;
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Future<Response> f = asyncHttpClient.prepareGet("http://www.ning.com/").execute(); //here you will execute async request
Response r = f.get(); // here you will block until respons is accessible;
所以我想如果需要,AsyncHttpClient
被设计为Sync
,因为这段代码会阻塞并等待响应。当您在一段时间后调用get()
时,可能会立即访问响应,因为请求已在此期间完成。
现在在新线程中运行两个部分,执行和响应reding,或者在主线程中执行请求,并等待后台线程中的响应(get()
部分) - 瞧