使用CDN:https://socket.io/zh-CN/docs/v4/client-installation/
socket.on 监听服务端的事件
socket.emit 是客户端的事件
<!DOCTYPE html>
<html>
<head><title>长时间任务</title><script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.js"></script><script>var socket = io('https://server-domain.com');// 1. 连接服务器socket.on('connect', function() {console.log('已连接到服务器');});// 2. 服务端事件 'task_started','task_completed'socket.on('task_started', function(data) {console.log('任务开始:', data.task_status);});socket.on('task_completed', function(data) {console.log('任务完成:', data);});// 客户端事件 'run_longtask',发送消息给服务器function startLongTask() { console.log('longtask任务'); var taskData = {video_path: '',gaili: 90,save_path: 'fczimg'};// 检查连接状态if (socket.connected) {// 3. 如果已连接,则直接发送任务信号socket.emit('run_longtask', taskData);} else {// 如果断开连接,则尝试重新连接socket.connect();// 监听连接成功事件socket.on('connect', function() {// 3. 连接成功后发送任务信号socket.emit('run_longtask', taskData);});}}function stopTask() {console.log('停止任务'); socket.emit('stop');}</script>
</head>
<body><button onclick="startLongTask()">启动长时间任务</button><button onclick="stopTask()">停止任务</button>
</body>
</html>