JAVA websocket 请求
时间: 2023-06-13 22:06:36 浏览: 119
java websocket
4星 · 用户满意度95%
下面是一个简单的Java WebSocket请求示例:
```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletionStage;
public class WebSocketClient {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create("wss://echo.websocket.org"), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("WebSocket opened");
webSocket.sendText("Hello, Server!");
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
System.out.println("Received message: " + data);
return null;
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("WebSocket closed: " + statusCode + " " + reason);
return null;
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.err.println("WebSocket error: " + error.getMessage());
}
}).join();
}
}
```
在此示例中,我们使用Java 11中的HttpClient API和WebSocket API。我们创建了一个WebSocket客户端,该客户端连接到一个WebSocket服务器,并在连接打开时发送“Hello,Server!”消息。当客户端收到消息时,它将在控制台上打印该消息。当连接关闭时,它将在控制台上打印状态代码和原因。如果发生错误,则在控制台上打印错误消息。
阅读全文