Documentation ¶
Index ¶
- type Conn
- type WS
- func (ws *WS) Close(sid string) error
- func (ws *WS) GetAllSID() []string
- func (ws *WS) Handler(w http.ResponseWriter, req *http.Request)
- func (ws *WS) Read(s *cs.Srv) (string, *cs.Request, error)
- func (ws *WS) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (ws *WS) Srv() *cs.Srv
- func (ws *WS) Write(sid string, resp *cs.Response) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type WS ¶
WS websocket 适配器
func New ¶
func New() *WS
New 实例化 websocket 适配器
Example ¶
package main import ( "errors" "log" "net/http" "time" "github.com/eyasliu/cs" "github.com/eyasliu/cs/xwebsocket" ) func main() { // 初始化 websocket ws := xwebsocket.New() http.Handle("/ws", ws) srv := ws.Srv() srv.Use(srv.AccessLogger("MYSRV")). // 打印请求响应日志 Use(cs.Recover()) // 统一错误处理,消化 panic 错误 srv.Handle("register", func(c *cs.Context) { // 定义请求数据 var body struct { UID int `p:"uid" v:"required"` Name string `p:"name" v:"required|min:4#必需指定名称|名称长度必需大于4位"` } // 解析请求数据 if err := c.Parse(&body); err != nil { c.Err(err, 401) return } // 设置会话状态数据 c.Set("uid", body.UID) c.Set("name", body.Name) // 响应消息 c.OK(map[string]interface{}{ "timestamp": time.Now().Unix(), }) // 给所有连接广播消息 c.Broadcast(&cs.Response{ Cmd: "someone_online", Data: body, }) // 往当前连接主动推送消息 c.Push(&cs.Response{ Cmd: "welcome", Data: "welcome to register my server", }) // 遍历所有在线会话,获取其他会话的状态,并往指定会话推送消息 for _, sid := range c.GetAllSID() { if c.Srv.GetState(sid, "uid") != nil { c.Srv.Push(sid, &cs.Response{ Cmd: "firend_online", Data: "your firend is online", }) } } }) // 分组 group := srv.Group(func(c *cs.Context) { // 过滤指定请求 if _, ok := c.Get("uid").(int); !ok { c.Err(errors.New("unregister session"), 101) return } c.Next() }) group.Handle("userinfo", func(c *cs.Context) { uid := c.Get("uid").(int) // 中间件已处理过,可大胆断言 c.OK(map[string]interface{}{ "uid": uid, }) }) go srv.Run() log.Fatal(http.ListenAndServe(":8080", nil)) }
Output:
func (*WS) Handler ¶
func (ws *WS) Handler(w http.ResponseWriter, req *http.Request)
Handler impl http.HandlerFunc to upgrade to websocket protocol
Click to show internal directories.
Click to hide internal directories.