You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.5 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

//go:build server || (!server && !client)
package main
import (
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/noahlann/nnet/pkg/nnet"
)
// This example demonstrates file-based session storage.
// Sessions are persisted to disk and survive server restarts.
func main() {
cfg := &nnet.Config{
Addr: "tcp://:8083",
Session: &nnet.SessionConfig{
Storage: "file", // 使用文件存储
Path: "./sessions_example", // Session文件存储路径
Expiration: 1 * time.Hour, // Session过期时间
},
Codec: &nnet.CodecConfig{
DefaultCodec: "json",
EnableProtocolEncode: false,
},
}
srv, err := nnet.NewServer(cfg)
if err != nil {
log.Fatal("create server:", err)
}
// 路由1设置Session值
srv.Router().RegisterString("set", func(ctx nnet.Context) error {
// 注意Session功能可能需要在服务器层面集成
// 这里演示如何使用Session的概念
// 实际使用中Session应该通过Connection或Context访问
connID := ctx.Connection().ID()
return ctx.Response().Write(map[string]any{
"action": "set",
"conn_id": connID,
"message": "session storage configured (file)",
"path": cfg.Session.Path,
"note": "Session API integration pending",
})
})
// 路由2获取Session信息
srv.Router().RegisterString("get", func(ctx nnet.Context) error {
connID := ctx.Connection().ID()
return ctx.Response().Write(map[string]any{
"action": "get",
"conn_id": connID,
"storage": "file",
"path": cfg.Session.Path,
"expiration": cfg.Session.Expiration.String(),
})
})
// 路由3计数器演示Session持久化
srv.Router().RegisterString("counter", func(ctx nnet.Context) error {
connID := ctx.Connection().ID()
// 在实际实现中这里应该从Session读取和更新计数器
return ctx.Response().Write(map[string]any{
"conn_id": connID,
"message": "counter endpoint (session-based counting would be implemented here)",
"note": "Session storage: file",
})
})
log.Println("session_file_server listening on :8083")
log.Printf("Session storage: file (%s)", cfg.Session.Path)
log.Printf("Session expiration: %v", cfg.Session.Expiration)
if err := srv.Start(); err != nil {
log.Fatal("start server:", err)
}
defer srv.Stop()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down... Sessions are persisted to disk.")
}