当前位置: 首页>>代码示例>>Golang>>正文


Golang WSChannel.Close方法代码示例

本文整理汇总了Golang中github.com/b3log/wide/util.WSChannel.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang WSChannel.Close方法的具体用法?Golang WSChannel.Close怎么用?Golang WSChannel.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/b3log/wide/util.WSChannel的用法示例。


在下文中一共展示了WSChannel.Close方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: WSHandler

// WSHandler handles request of creating session channel.
//
// When a channel closed, releases all resources associated with it.
func WSHandler(w http.ResponseWriter, r *http.Request) {
	sid := r.URL.Query()["sid"][0]

	conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
	wsChan := util.WSChannel{Sid: sid, Conn: conn, Request: r, Time: time.Now()}

	ret := map[string]interface{}{"output": "Session initialized", "cmd": "init-session"}
	err := wsChan.WriteJSON(&ret)
	if nil != err {
		return
	}

	SessionWS[sid] = &wsChan

	wSession := WideSessions.Get(sid)
	if nil == wSession {
		httpSession, _ := HTTPSession.Get(r, "wide-session")

		if httpSession.IsNew {
			return
		}

		httpSession.Options.MaxAge = conf.Wide.HTTPSessionMaxAge
		httpSession.Save(r, w)

		wSession = WideSessions.new(httpSession, sid)

		logger.Tracef("Created a wide session [%s] for websocket reconnecting, user [%s]", sid, wSession.Username)
	}

	logger.Tracef("Open a new [Session Channel] with session [%s], %d", sid, len(SessionWS))

	input := map[string]interface{}{}

	wsChan.Conn.SetReadDeadline(time.Now().Add(pongWait))
	wsChan.Conn.SetPongHandler(func(string) error { wsChan.Conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	ticker := time.NewTicker(pingPeriod)

	defer func() {
		WideSessions.Remove(sid)
		ticker.Stop()
		wsChan.Close()
	}()

	// send websocket ping message.
	go func(t *time.Ticker, channel util.WSChannel) {
		for {
			select {
			case <-t.C:
				if err := channel.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
					return
				}
			}
		}

	}(ticker, wsChan)

	for {
		if err := wsChan.ReadJSON(&input); err != nil {
			logger.Tracef("[Session Channel] of session [%s] disconnected, releases all resources with it, user [%s]", sid, wSession.Username)

			return
		}

		ret = map[string]interface{}{"output": "", "cmd": "session-output"}

		if err := wsChan.WriteJSON(&ret); err != nil {
			logger.Error("Session WS ERROR: " + err.Error())

			return
		}

		wsChan.Time = time.Now()
	}
}
开发者ID:rdterner,项目名称:wide,代码行数:78,代码来源:sessions.go


注:本文中的github.com/b3log/wide/util.WSChannel.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。