ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] > [参考](https://github.com/olahol/melody) ## 概述 支持 gin ,echo ### 可以查看官方的demo ## demo ### 移动纸人 > [完整 demo](https://github.com/olahol/melody/tree/master/examples/gophers) <details> <summary>main.go</summary> ``` package main import ( "github.com/gin-gonic/gin" "gopkg.in/olahol/melody.v1" "net/http" "strconv" "strings" "sync" ) type GopherInfo struct { ID, X, Y string } func main() { router := gin.Default() mrouter := melody.New() gophers := make(map[*melody.Session]*GopherInfo) lock := new(sync.Mutex) counter := 0 router.GET("/", func(c *gin.Context) { http.ServeFile(c.Writer, c.Request, "index.html") }) router.GET("/ws", func(c *gin.Context) { mrouter.HandleRequest(c.Writer, c.Request) }) mrouter.HandleConnect(func(s *melody.Session) { lock.Lock() for _, info := range gophers { s.Write([]byte("set " + info.ID + " " + info.X + " " + info.Y)) } gophers[s] = &GopherInfo{strconv.Itoa(counter), "0", "0"} s.Write([]byte("iam " + gophers[s].ID)) counter += 1 lock.Unlock() }) mrouter.HandleDisconnect(func(s *melody.Session) { lock.Lock() mrouter.BroadcastOthers([]byte("dis "+gophers[s].ID), s) delete(gophers, s) lock.Unlock() }) mrouter.HandleMessage(func(s *melody.Session, msg []byte) { p := strings.Split(string(msg), " ") lock.Lock() info := gophers[s] if len(p) == 2 { info.X = p[0] info.Y = p[1] mrouter.BroadcastOthers([]byte("set "+info.ID+" "+info.X+" "+info.Y), s) }else if p[0]=="bui" { mrouter.BroadcastOthers([]byte("bui "+p[1]+" "+p[2]), s) } lock.Unlock() }) router.Run(":5000") } ``` </details> <br/>