websocket实现java长连接,加代码
时间: 2023-08-29 20:12:55 浏览: 109
好的,下面是一个基于 Java 的 WebSocket 实现长连接的示例代码:
1. 首先,需要引入 Java WebSocket API 的依赖包,推荐使用 Tyrus,Maven 依赖如下:
```
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>1.13.1</version>
</dependency>
```
2. 创建 WebSocket 客户端:
```java
import javax.websocket.ClientEndpoint;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import java.io.IOException;
import java.net.URI;
@ClientEndpoint
public class WebSocketClient {
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
}
@OnMessage
public void onMessage(String message) {
// 处理收到的消息
}
@OnClose
public void onClose() {
// 关闭连接
}
public void connect(String url) throws Exception {
URI uri = new URI(url);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, uri);
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public void close() throws IOException {
this.session.close();
}
}
```
3. 在主函数中使用 WebSocketClient:
```java
public class Main {
public static void main(String[] args) throws Exception {
WebSocketClient client = new WebSocketClient();
client.connect("ws://localhost:8080/ws");
client.sendMessage("hello");
// ...
client.close();
}
}
```
以上代码仅为示例,实际应用中需要根据实际需求进行适当的修改。
阅读全文