java 调用websocket接口
时间: 2023-10-12 17:56:19 浏览: 113
要在Java中调用WebSocket接口,你可以使用Java提供的WebSocket API或者使用第三方库。下面是两种方法的示例:
1. 使用Java提供的WebSocket API:
```java
import javax.websocket.*;
import java.net.URI;
@ClientEndpoint
public class WebSocketClient {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server: " + session.getRequestURI());
}
@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);
}
public static void main(String[] args) {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
Session session = container.connectToServer(WebSocketClient.class, URI.create("ws://example.com/socket"));
// 可以在这里发送消息
session.getBasicRemote().sendText("Hello, server!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用第三方库例如Java-WebSocket(https://github.com/TooTallNate/Java-WebSocket):
```java
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
public class WebSocketClientExample extends WebSocketClient {
public WebSocketClientExample(URI serverUri) {
super(serverUri);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("Connected to server: " + getURI());
}
@Override
public void onMessage(String message) {
System.out.println("Received message: " + message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Connection closed: " + reason);
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
}
public static void main(String[] args) {
try {
WebSocketClientExample client = new WebSocketClientExample(new URI("ws://example.com/socket"));
client.connect();
// 可以在这里发送消息
client.send("Hello, server!");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
```
这些示例代码可以帮助你在Java中调用WebSocket接口。你需要将示例代码中的"ws://example.com/socket"替换为实际的WebSocket服务器地址。
阅读全文