java实现websocket请求
时间: 2023-11-09 17:03:18 浏览: 136
Java实现WebSocket请求需要使用Java WebSocket API。以下是一个简单的示例代码:
```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://example.com"), new WebSocketListener())
.join();
}
private static class WebSocketListener implements WebSocket.Listener {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("WebSocket opened");
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
System.out.println("Received message: " + data);
return null;
}
@Override
public void onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("WebSocket closed with status code " + statusCode + " and reason: " + reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.err.println("WebSocket error: " + error.getMessage());
}
}
}
```
在这个示例中,我们使用Java 11中的HttpClient和WebSocket API。我们创建了一个HttpClient实例,并使用它创建了一个WebSocket实例。我们还定义了一个WebSocket.Listener实现,以便在WebSocket打开、接收消息、关闭或出现错误时进行处理。
阅读全文