java 使用sebsocket进行倒计时
时间: 2023-07-11 09:19:18 浏览: 220
java 实现倒计时
4星 · 用户满意度95%
使用Java的WebSocket技术实现倒计时可以通过以下步骤:
1. 定义一个WebSocket服务器类,该类需要继承自javax.websocket.Endpoint类,并实现其onOpen、onClose、onMessage等方法。
```java
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
public class CountdownServer extends Endpoint {
private Session session;
public void onOpen(Session session, EndpointConfig config) {
this.session = session;
session.addMessageHandler(new MessageHandler.Whole<String>() {
public void onMessage(String message) {
int seconds = Integer.parseInt(message);
countdown(seconds);
}
});
}
public void onClose(Session session, CloseReason closeReason) {
// do nothing
}
private void countdown(int seconds) {
for (int i = seconds; i >= 0; i--) {
try {
session.getBasicRemote().sendText(String.valueOf(i));
Thread.sleep(1000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
2. 定义一个客户端页面,该页面需要引入WebSocket的JS库,并连接WebSocket服务器。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Countdown</title>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
<script type="text/javascript">
var sock = new SockJS('http://localhost:8080/countdown');
sock.onmessage = function (event) {
document.getElementById("countdown").innerHTML = event.data;
};
function startCountdown() {
var seconds = document.getElementById("seconds").value;
sock.send(seconds);
}
</script>
</head>
<body>
<h1>Countdown</h1>
<input type="number" id="seconds" placeholder="Seconds">
<button onclick="startCountdown()">Start</button>
<p id="countdown"></p>
</body>
</html>
```
3. 启动WebSocket服务器,并在客户端页面中访问倒计时页面。
```java
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/countdown")
public class CountdownServerEndpoint {
public static void main(String[] args) {
org.glassfish.tyrus.server.Server server =
new org.glassfish.tyrus.server.Server("localhost", 8080, "/", null,
CountdownServer.class);
try {
server.start();
System.out.println("WebSocket server started");
Thread.currentThread().join();
} catch (Exception e) {
e.printStackTrace();
} finally {
server.stop();
}
}
}
```
以上就是使用Java的WebSocket技术实现倒计时的步骤。当然,具体实现还需要根据具体的业务需求和技术实现细节进行调整。
阅读全文