java发送websocket请求
时间: 2023-10-24 20:16:41 浏览: 86
java websocket
5星 · 资源好评率100%
Java可以使用Java WebSocket API来发送WebSocket请求。以下是一个简单的示例代码,可以使用Java WebSocket API连接到WebSocket服务器并发送消息:
```java
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
@ClientEndpoint
public class WebSocketClient {
private final CountDownLatch latch;
private Session session;
public WebSocketClient() {
this.latch = new CountDownLatch(1);
}
public void connect(String uri) throws Exception {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, new URI(uri));
latch.await(10, TimeUnit.SECONDS);
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
latch.countDown();
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("WebSocket closed: " + closeReason);
}
public void sendMessage(String message) throws Exception {
session.getBasicRemote().sendText(message);
}
public static void main(String[] args) throws Exception {
WebSocketClient client = new WebSocketClient();
client.connect("ws://localhost:8080/websocket");
client.sendMessage("Hello, WebSocket!");
}
}
```
在上面的示例代码中,我们定义了一个`WebSocketClient`类,它实现了`javax.websocket.ClientEndpoint`接口。我们使用`WebSocketContainer`来连接到WebSocket服务器并发送消息。`@OnOpen`注解用于在连接建立时调用的方法,`@OnMessage`注解用于接收消息时调用的方法,`@OnClose`注解用于在连接关闭时调用的方法。我们可以使用`Session`对象来发送WebSocket消息。在`main`方法中,我们创建一个`WebSocketClient`对象并连接到WebSocket服务器,然后发送消息。
阅读全文