java中用websocket实现及时通讯的代码
时间: 2023-09-22 12:09:15 浏览: 89
下面是一个简单的示例代码,演示如何在Java中使用WebSocket实现即时通讯:
1. WebSocket服务器端代码:
```java
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@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 from client: " + message);
session.getBasicRemote().sendText("Server received: " + message);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
System.out.println("WebSocket connection closed: " + session.getId() + ", Reason: " + closeReason.getReasonPhrase());
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("WebSocket error occurred: " + throwable.getMessage());
}
}
```
2. WebSocket客户端代码:
```java
import javax.websocket.*;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
@ClientEndpoint
public class WebSocketClient {
private static CountDownLatch latch;
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocket connection opened: " + session.getId());
try {
session.getBasicRemote().sendText("Hello from client");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Received message from server: " + message);
latch.countDown();
}
@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(Session session, Throwable throwable) {
System.out.println("WebSocket error occurred: " + throwable.getMessage());
latch.countDown();
}
public static void main(String[] args) throws Exception {
latch = new CountDownLatch(1);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
Session session = container.connectToServer(WebSocketClient.class, new URI("ws://localhost:8080/websocket"));
latch.await();
session.close();
}
}
```
这个示例代码中,WebSocket服务器端通过`@ServerEndpoint`注解指定了WebSocket的端点URL为`/websocket`。当有客户端连接、发送消息、关闭连接或出现错误时,相应的回调方法会被触发。WebSocket客户端使用`ContainerProvider.getWebSocketContainer()`获取WebSocketContainer实例,并通过`connectToServer()`方法连接到服务器端。
请注意,这只是一个简单的示例,您可以根据自己的需求进行修改和扩展。另外,您需要确保在部署服务器时配置正确的WebSocket容器和URL。
阅读全文