Java Websocket等待响应,然后再向同一套接字发出下一个请求

时间:2019-02-13 08:59:41

标签: java websocket

public WebSocket connect() throws Exception {
WebSocket ws = new WebSocketFactory().setConnectionTimeout(TIMEOUT).createSocket(SERVER)
.addListener(new WebSocketAdapter() {
public void onTextMessage(WebSocket websocket, String message) {
System.out.println(message);
}

public void onConnected(WebSocket websocket, java.util.Map headers) {
System.out.println(websocket.getSocket().toString());
System.out.println(headers.toString());
logger.logInfo("QlikWebConnector", "connect", "connection: ",
websocket.getSocket().toString() + headers.toString());
}

public void onMessageError(com.neovisionaries.ws.client.WebSocket websocket,
com.neovisionaries.ws.client.WebSocketException cause, java.util.List frames)
throws java.lang.Exception {
}

public void onSendError(com.neovisionaries.ws.client.WebSocket websocket,
com.neovisionaries.ws.client.WebSocketException cause,
com.neovisionaries.ws.client.WebSocketFrame frame) throws java.lang.Exception {
}

public void onBinaryMessage(com.neovisionaries.ws.client.WebSocket websocket, byte[] binary)
throws java.lang.Exception {
}

public void onDisconnected(com.neovisionaries.ws.client.WebSocket websocket,
com.neovisionaries.ws.client.WebSocketFrame serverCloseFrame,
com.neovisionaries.ws.client.WebSocketFrame clientCloseFrame, boolean closedByServer)
throws java.lang.Exception {
}
}).addExtension(WebSocketExtension.PERMESSAGE_DEFLATE).connect();
if (ws.isOpen()) {
System.out.println("websocket is open ");
logger.logInfo("QlikWebConnector", "connect", "websocket is open: ", "websocket is open");
}
return ws;
}

我正在发送以下请求: 1)ws.sendText(“我的message1”)2)ws.sendText(“我的message2”)

发生了什么事? 1)两个请求都同时被触发。

问题/预期:- 1)我希望我的套接字等到第一个请求得到处理,因为我的第二个请求取决于第一个请求的响应。

有线索吗?

1 个答案:

答案 0 :(得分:0)

您可以执行的一种方法是稍微更改程序的逻辑。例如,您可以发送第一条消息并侦听响应,而不是同时在同一地点发送两条消息。在收到第一条消息的回复后-您可以发送第二条消息。

类似这样的东西:

public void onTextMessage(WebSocket websocket, String message) {
    if (shouldSendSeccondMessage(message)) {
        sendSeccondMessage();
    }
}

如果您有某种状态,并根据状态发送特定的消息-那么您可以考虑使用State pattern。因此,对于每条消息,您的状态机将决定下一步(消息)。