java调用websocket
时间: 2023-06-30 09:11:22 浏览: 75
Java调用WebSocket可以使用Java API for WebSocket,以下是一个简单的示例代码:
```java
import javax.websocket.*;
@ClientEndpoint
public class WebSocketClient {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server: " + session.getId());
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Connection closed: " + closeReason.getReasonPhrase());
}
public static void main(String[] args) throws Exception {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(WebSocketClient.class, new URI("ws://localhost:8080/ws"));
session.getBasicRemote().sendText("Hello, server!");
}
}
```
在`@ClientEndpoint`注解中标识了这是一个WebSocket客户端类。`@OnOpen`注解表示连接建立后会触发该方法,`@OnMessage`注解表示接收到消息后会触发该方法,`@OnClose`注解表示连接关闭后会触发该方法。在`main`方法中使用`WebSocketContainer`连接到WebSocket服务器,并可以通过`Session`对象发送消息。
阅读全文