func (wsConn *WSConn) write(b []byte) { if len(wsConn.writeChan) == cap(wsConn.writeChan) { log.Debug("close conn: channel full") wsConn.destroy() return } wsConn.writeChan <- b }
func (tcpConn *TCPConn) doWrite(b []byte) { if len(tcpConn.writeChan) == cap(tcpConn.writeChan) { log.Debug("close conn: channel full") tcpConn.doDestroy() return } tcpConn.writeChan <- b }
func (server *TCPServer) run() { server.wgLn.Add(1) defer server.wgLn.Done() var tempDelay time.Duration for { conn, err := server.ln.Accept() if err != nil { if ne, ok := err.(net.Error); ok && ne.Temporary() { if tempDelay == 0 { tempDelay = 5 * time.Millisecond } else { tempDelay *= 2 } if max := 1 * time.Second; tempDelay > max { tempDelay = max } log.Info("accept error: %v; retrying in %v", err, tempDelay) time.Sleep(tempDelay) continue } return } tempDelay = 0 server.mutexConns.Lock() if len(server.conns) >= server.MaxConnNum { server.mutexConns.Unlock() conn.Close() log.Debug("too many connections") continue } server.conns[conn] = struct{}{} server.mutexConns.Unlock() server.wgConns.Add(1) tcpConn := newTCPConn(conn, server.PendingWriteNum, server.msgParser) agent := server.NewAgent(tcpConn) go func() { agent.Run() // cleanup tcpConn.Close() server.mutexConns.Lock() delete(server.conns, conn) server.mutexConns.Unlock() agent.OnClose() server.wgConns.Done() }() } }
func (handler *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } conn, err := handler.upgrader.Upgrade(w, r, nil) if err != nil { log.Debug("upgrade error: %v", err) return } conn.SetReadLimit(int64(conf.Env.MaxMsgLen)) handler.wg.Add(1) defer handler.wg.Done() handler.mutexConns.Lock() if handler.conns == nil { handler.mutexConns.Unlock() conn.Close() return } if len(handler.conns) >= conf.Env.MaxConnNum { handler.mutexConns.Unlock() conn.Close() log.Debug("too many connections") return } handler.conns[conn] = struct{}{} handler.mutexConns.Unlock() wsConn := NewWSConn(conn) agent := handler.newAgent(wsConn) agent.Run() wsConn.Close() handler.mutexConns.Lock() delete(handler.conns, conn) handler.mutexConns.Unlock() agent.OnClose() }
func (a *agent) Run() { for { data, err := a.conn.ReadMsg() if err != nil { log.Debug("read message: %v", err) break } if a.gate.Processor != nil { msg, err := a.gate.Processor.Unmarshal(data) if err != nil { log.Debug("unmarshal message error: %v", err) break } err = a.gate.Processor.Route(msg, a) if err != nil { log.Debug("route message error: %v", err) break } } } }
func (gate *Gate) OnDestroy() { log.Debug("gate service destoryed.") }