//{"pkg":"message","from":1,"to":1,"msg":"hahahaha"} func handleMsg(msg *map[string]interface{}, c *Client, body []byte) { switch (*msg)["pkg"] { case "iq": log.Info("iq:", (*msg)["msg"]) case "message": to := (*msg)["to"] tocil, ok := c.mgr.Sessions[int64(to.(float64))] if ok { tocil.writer.WriteString(fmt.Sprintf("%v >>> %s \r\n", (*msg)["from"].(float64), (*msg)["msg"].(string))) tocil.writer.Flush() } default: log.Info(fmt.Println("unknow package:", string(body))) } }
func (this *Client) listener() { defer connClose(this) for { d, _, err := this.reader.ReadLine() if err != nil { if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() { log.Info("timeout") } log.Info("e1:" + err.Error()) return } else { this.ci <- d (*this.Conn).SetDeadline(time.Now().Add(TimeOutValue * time.Second)) } } }
func (self *ConnMgr) NewSession(c *net.Conn) *Client { clt := Client{Conn: c, ci: make(chan []byte, 8), co: make(chan []byte, 8), mgr: self} (*clt.Conn).SetDeadline(time.Now().Add(TimeOutValue * time.Second)) radd := (*c).RemoteAddr().String() clt.mate = &Matedata{radd: &radd} self.Count += 1 clt.mate.id = self.Count self.Sessions[self.Count] = &clt log.Info("session count=", self.Count) return &clt }
func connClose(c *Client) { if err := (*c.Conn).Close(); err == nil { v := c.mate.id (*c.mgr).remove(v) c.live = false close(c.ci) close(c.co) } else { log.Info("close %s failed...", (*c.Conn).RemoteAddr().String()) } }