gpt4 book ai didi

java - 创建一个线程来发送并等待响应(websockets)

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

有一个方法来连接到套接字并发送消息并 hibernate 一秒钟来处理响应。

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 秒,使用 AsyncHttpClient 连接到套接字,这不是阻塞 io。我想创建一个可以发送消息并等待服务器响应的线程?我确实尝试通过实现可运行接口(interface)来创建一个类,但没有成功!有关如何创建对 websockets 或阻塞 IO 的同步调用的任何建议。

更新:使用同步块(synchronized block)来等待,然后在收到消息后通知!关注了 @Antoniossss 评论

最佳答案

直接来自 Ning 主页

    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() 时,可能会立即访问响应,因为请求已同时完成。

现在在新线程中运行这两个部分,执行和响应红色,或者在主线程中执行请求,并在后台线程中等待响应(get()部分) - 瞧

关于java - 创建一个线程来发送并等待响应(websockets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25892364/

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