// server.js import { serve } from "https://deno.land/std@0.170.0/http/server.ts"; import { WebSocket, acceptWebSocket, isWebSocketCloseEvent } from "https://deno.land/std@0.170.0/ws/mod.ts"; // 初始产品数据 let products = [ { id: 1, name: "紫檀木朱砂手串", description: "精选上等紫檀木,搭配纯天然朱砂,手工打磨抛光,富有光泽,具有安神助眠之功效。", price: 1280, material: "紫檀木+天然朱砂", size: "直径12mm", category: "手串", image: "https://images.unsplash.com/photo-1601924994987-69e26d50dc26?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80" }, { id: 2, name: "红木雕花笔筒", description: "采用整块红木精雕细琢而成,表面刻有梅兰竹菊四君子图案,展现传统木雕工艺之美。", price: 980, material: "红木", size: "高12cm 直径8cm", category: "文房", image: "https://images.unsplash.com/photo-1601924994987-69e26d50dc26?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80" }, { id: 3, name: "朱砂原石摆件", description: "天然朱砂原石,未经雕琢,保留自然形态,色泽鲜艳,能量充沛。", price: 2200, material: "天然朱砂", size: "高15cm 宽10cm", category: "摆件", image: "https://images.unsplash.com/photo-1601924994987-69e26d50dc26?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80" }, { id: 4, name: "沉香木雕观音像", description: "上等沉香木雕刻而成,观音法相庄严,雕工精细,香气持久。", price: 5800, material: "沉香木", size: "高25cm 宽15cm", category: "雕像", image: "https://images.unsplash.com/photo-1601924994987-69e26d50dc26?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80" } ]; // 存储所有连接的客户端 const clients = new Set(); let visitCount = 0; // 处理WebSocket连接 async function handleWebSocket(sock) { clients.add(sock); console.log("新的客户端连接"); visitCount++; try { for await (const ev of sock) { if (typeof ev === "string") { // 文本消息 try { const data = JSON.parse(ev); if (data.action === 'subscribe') { // 订阅频道 - 这里我们只处理一个频道 console.log(`客户端订阅了更新`); } else if (data.action === 'updateProducts') { // 更新产品数据 products = data.products; console.log("产品列表已更新"); // 广播更新给所有客户端 broadcastToAll({ action: 'updateProducts', products: products }); } else if (data.action === 'getProducts') { // 发送当前产品列表 sock.send(JSON.stringify({ action: 'updateProducts', products: products })); } } catch (e) { console.error("处理消息时出错:", e); } } else if (isWebSocketCloseEvent(ev)) { // 连接关闭 console.log("客户端断开连接"); clients.delete(sock); break; } } } catch (err) { console.error("处理WebSocket失败:", err); clients.delete(sock); } } // 广播消息给所有客户端 function broadcastToAll(message) { const messageStr = JSON.stringify(message); for (const client of clients) { if (!client.isClosed) { try { client.send(messageStr); } catch (e) { console.error("广播消息失败:", e); } } } } // HTTP服务器请求处理 async function handleRequest(req) { if (req.headers.get("upgrade") === "websocket") { // WebSocket升级请求 const { socket, response } = Deno.upgradeWebSocket(req); handleWebSocket(socket); return response; } // 普通HTTP请求 return new Response(`
服务器状态: 运行中
连接客户端数: ${clients.size}
产品数量: ${products.length}
总访问次数: ${visitCount}