增加socketio server 支持

This commit is contained in:
yourname
2025-05-15 07:29:09 +00:00
parent bc953bcd43
commit b879ad4f7c
5 changed files with 124 additions and 25 deletions

15
server/routes_socketio.ts Normal file
View File

@@ -0,0 +1,15 @@
import { Socket, Server } from "socket.io";
export function setupSocketIO(io: Server) {
io.on("connection", (socket: Socket) => {
console.log(`socket ${socket.id} connected`);
socket.emit("hello", "world");
socket.on("disconnect", (reason) => {
console.log(`socket ${socket.id} disconnected due to ${reason}`);
});
// 可在此添加更多socket事件处理
});
}

View File

@@ -3,6 +3,9 @@ import { Hono } from 'hono'
import { APIClient } from '@d8d-appcontainer/api'
import debug from "debug"
import { cors } from 'hono/cors'
import { Server } from "socket.io"
import httpServer from './app.tsx'
import { setupSocketIO } from './routes_socketio.ts'
// 初始化debug实例
const log = {
@@ -37,41 +40,52 @@ const getApiClient = async (workspaceKey: string, serverUrl?: string) => {
}
}
// 初始化API Client
// 注意WORKSPACE_KEY 需要在 多八多(www.d8d.fun) 平台注册并开通工作空间后获取
const workspaceKey = Deno.env.get('WORKSPACE_KEY') || ''
if (!workspaceKey) {
console.warn('未设置WORKSPACE_KEY请前往 多八多(www.d8d.fun) 注册并开通工作空间以获取密钥')
}
const apiClient = await getApiClient(workspaceKey)
// 创建Hono应用实例
const app = new Hono()
// 注册CORS中间件
app.use('/*', cors())
// 创建Socket.IO实例
const io = new Server({
cors: {
origin: "*",
methods: ["GET", "POST"],
credentials: true
}
})
setupSocketIO(io);
// 动态加载并运行模板
const runTemplate = async () => {
try {
// 创建基础app实例
const moduleApp = new Hono()
// 初始化API Client
// 注意WORKSPACE_KEY 需要在 多八多(www.d8d.fun) 平台注册并开通工作空间后获取
const workspaceKey = Deno.env.get('WORKSPACE_KEY') || ''
if (!workspaceKey) {
console.warn('未设置WORKSPACE_KEY请前往 多八多(www.d8d.fun) 注册并开通工作空间以获取密钥')
}
const apiClient = await getApiClient(workspaceKey)
// 导入模板主模块
const templateModule = await import('./app.tsx')
if (templateModule.default) {
// 传入必要参数并初始化应用
const appInstance = templateModule.default({
apiClient: apiClient,
app: moduleApp,
moduleDir: './'
})
// 启动服务器
Deno.serve({ port: 8080 }, appInstance.fetch)
console.log('应用已启动,监听端口: 8080')
}
// 传入必要参数并初始化应用
const appInstance = httpServer({
apiClient: apiClient,
app: moduleApp,
moduleDir: './'
})
// 启动服务器
Deno.serve({
handler: io.handler(async (req) => {
return await appInstance.fetch(req) || new Response(null, { status: 404 });
}),
port: 8080
})
console.log('应用已启动,监听端口: 8080')
} catch (error) {
console.error('模板加载失败:', error)
}