java websocket实现长连接,附加代码实现
时间: 2023-09-08 13:15:07 浏览: 170
Java中可以使用Java WebSocket API实现WebSocket长连接。下面是一个简单的示例代码:
服务端代码:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
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 {
private Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("WebSocket opened: " + session.getId());
}
@OnMessage
public void onMessage(String message) {
System.out.println("Message received: " + message);
try {
session.getBasicRemote().sendText("Received message: " + message);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnClose
public void onClose() {
System.out.println("WebSocket closed");
}
@OnError
public void onError(Throwable t) {
System.out.println("WebSocket error: " + t.getMessage());
}
public static void main(String[] args) throws Exception {
org.glassfish.tyrus.server.Server server = new org.glassfish.tyrus.server.Server("localhost", 8080, "/websocket", WebSocketServer.class);
server.start();
System.out.println("WebSocket server started");
Thread.currentThread().join();
}
}
```
客户端代码:
```java
import java.net.URI;
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 Session session;
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("WebSocket opened: " + session.getId());
}
@OnMessage
public void onMessage(String message) {
System.out.println("Message received: " + message);
}
@OnClose
public void onClose(CloseReason reason) {
System.out.println("WebSocket closed: " + reason);
}
@OnError
public void onError(Throwable t) {
System.out.println("WebSocket error: " + t.getMessage());
}
public static void main(String[] args) throws Exception {
WebSocketContainer container = javax.websocket.ContainerProvider.getWebSocketContainer();
WebSocketClient client = new WebSocketClient();
container.connectToServer(client, new URI("ws://localhost:8080/websocket"));
System.out.println("WebSocket client started");
}
}
```
这个示例代码使用了Tyrus作为WebSocket实现,可以使用Maven添加依赖:
```xml
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-server</artifactId>
<version>1.17.1</version>
</dependency>
```
当然,也可以使用其他的Java WebSocket实现库。
阅读全文