java websocket实现长连接 附加代码实现
时间: 2023-08-29 10:13:12 浏览: 164
Java中实现Websocket长连接可以使用Java API中提供的javax.websocket.*类库,下面是一个简单的示例代码:
Server端:
```java
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket")
public class WebSocketServer {
@OnOpen
public void onOpen(Session session) {
System.out.println("Websocket connection opened: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("Received message: " + message);
session.getBasicRemote().sendText("Server received: " + message);
}
@OnClose
public void onClose(Session session) {
System.out.println("Websocket connection closed: " + session.getId());
}
@OnError
public void onError(Throwable t) {
System.out.println("Websocket error: " + t.getMessage());
}
}
```
Client端:
```java
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
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;
public WebSocketClient() {
latch = new CountDownLatch(1);
}
public void connect(String uri) throws URISyntaxException, InterruptedException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, new URI(uri));
latch.await();
}
@OnOpen
public void onOpen(Session session) {
System.out.println("Websocket connection opened: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Received message: " + message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("Websocket connection closed: " + session.getId() + ", reason: " + closeReason.getReasonPhrase());
latch.countDown();
}
@OnError
public void onError(Throwable t) {
System.out.println("Websocket error: " + t.getMessage());
latch.countDown();
}
}
```
这里以Java API提供的javax.websocket.*类库为例,客户端和服务端的代码都非常简单明了。
服务端使用@ServerEndpoint注解标识一个类作为WebSocket服务器端点。在该类中,通过@OnOpen、@OnMessage、@OnClose和@OnError注解定义了WebSocket连接打开、接收消息、连接关闭以及发生错误时的处理逻辑。
客户端则使用@ClientEndpoint注解标识一个类作为WebSocket客户端端点。在该类中,通过@OnOpen、@OnMessage、@OnClose和@OnError注解定义了WebSocket连接打开、接收消息、连接关闭以及发生错误时的处理逻辑。在connect方法中通过WebSocketContainer.connectToServer方法连接到服务端,并通过CountDownLatch来保证连接成功后代码的运行。
阅读全文