java发送websocket请求
时间: 2023-09-05 16:13:43 浏览: 87
你可以使用Java的WebSocket API来发送WebSocket请求。下面是一个简单的示例代码:
```java
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
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.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
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 DeploymentException, URISyntaxException, InterruptedException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, new URI(uri));
this.latch.await(10, TimeUnit.SECONDS);
}
public void sendMessage(String message) {
this.session.getAsyncRemote().sendText(message);
}
public void sendBinary(ByteBuffer buffer) {
this.session.getAsyncRemote().sendBinary(buffer);
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
this.latch.countDown();
}
@OnClose
public void onClose(CloseReason reason) {
System.out.println("Connection closed: " + reason);
}
@OnError
public void onError(Throwable cause) {
System.out.println("Error: " + cause.getMessage());
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@OnMessage
public void onMessage(ByteBuffer buffer) {
System.out.println("Received binary message: " + buffer);
}
}
```
你可以使用`WebSocketClient`类来连接WebSocket服务器并发送消息。以下是使用示例:
```java
public static void main(String[] args) {
try {
WebSocketClient client = new WebSocketClient();
client.connect("wss://example.com/ws");
client.sendMessage("Hello, world!");
} catch (Exception e) {
e.printStackTrace();
}
}
```
在上面的示例中,我们创建了一个`WebSocketClient`实例,并使用`connect()`方法连接到WebSocket服务器。一旦连接成功,我们可以使用`sendMessage()`方法发送文本消息,或使用`sendBinary()`方法发送二进制消息。在接收到消息时,`onMessage()`方法将被调用。
阅读全文