使用VertX HttpClient访问AWS WebSocket



我在AWS上创建了一个带有Web套接字的API网关。我想使用VertX提供的HttpClient连接到它。我为客户端垂直使用以下代码:

public class WebSocketClient extends AbstractVerticle {
// application address replaced by [address]
protected final String host = "[address].execute-api.us-east-1.amazonaws.com";
protected final String path = "/dev";
protected final int port = 80;
protected final String webSocketAddress = "wss://[address].execute-api.us-east-1.amazonaws.com/dev";
@Override
public void start() throws Exception {
startClient(this.vertx);
}
protected void startClient(Vertx vertx) {
HttpClient client = vertx.createHttpClient();
client.webSocket(port, host, path, asyncWebSocket -> {
if (asyncWebSocket.succeeded()) {
WebSocket socket = asyncWebSocket.result();
System.out.println("Successfully connected. Node closing.");
socket.close().onFailure(throwable -> {
throwable.printStackTrace();
});
} else {
asyncWebSocket.cause().printStackTrace();
}
});
}
}

当我使用运行在本地主机上的VertX服务器进行测试时,相同的代码可以工作,因此我认为这是正确的WebSocketConnectionOptions的问题。

当我尝试使用HttpClient垂直连接到AWS套接字时,我得到一个"连接被拒绝";错误。使用wscat连接到它没有问题。

谢谢你的帮助。

这个问题基本上是在处理同样的问题。我将在这里发布解决方案,只是为了记录一种直接使用AWS ApiGateway Websockets与VertX的方法。

因此,目标是实现一个连接到已部署的AWS Api WebSocket网关的VertX WebClient,该网关可以在WsUri "wss://[address].execute-api.us-east-1.amazonaws.com/dev"(你必须将[address]替换为ApiGateway Websocket的地址)

下面是设置WebClient,连接到Websocket,打印成功消息,然后再次断开连接的代码:

public class WebSocketClient extends AbstractVerticle {
protected final String webSocketUrl = "wss://[address].execute-api.us-east-1.amazonaws.com/dev"    
protected final String host = "[address].execute-api.us-east-1.amazonaws.com";
protected final String path = "/dev";
protected final int sslPort = 443;

@Override
public void start() throws Exception {
startClient(this.vertx);
}
protected void startClient(Vertx vertx) {
HttpClient client = vertx
.createHttpClient(new 
HttpClientOptions().setDefaultHost(host).setDefaultPort(sslPort).setSsl(true));
// connect to the web socket
client.webSocket(path, asyncWebSocket -> {            
if (asyncWebSocket.succeeded()) {
// executed on a successful connection
WebSocket socket = asyncWebSocket.result(); // use this for further communication                
System.out.println("Successfully connected. Closing the socket.");
// Closing the socket
socket.close().onFailure(throwable -> {
throwable.printStackTrace();
});
} else {
// executed if the connection attempt fails
asyncWebSocket.cause().printStackTrace();
}
});
}

你可以使用下面的类来运行这个例子:

public class PlayWebSocket {
public static void main(String[] args) throws URISyntaxException{
Vertx vertx = Vertx.vertx();
WebSocketClient clientVerticle = new WebSocketClient();
vertx.deployVerticle(clientVerticle);
}
}

在Java端,这应该打印关于连接成功和套接字关闭的消息。在AWS端,应该调用ApiGateway的$connect和$disconnect方法。您可以使用CloudWatch在处理程序函数的日志中检查这一点。

相关内容

  • 没有找到相关文章

最新更新