func (c *Client) Response(msg *protocol.DataPackage) error { head := msg.Head tail := msg.Tail if (head.Command == protocol.CLIENT_CMD_USER_LOGIN || head.Command == protocol.CLIENT_CMD_USER_REGISTER) && tail.UID != 0 { c.Uid = tail.UID c.Stat = CLIENT_STATE_ONLINE } buf := protocol.GetBuffer() defer protocol.PutBuffer(buf) binary.Write(buf, binary.BigEndian, head) binary.Write(buf, binary.BigEndian, msg.BodyData()) // write to Conn c.Conn.SetDeadline(time.Now().Add(NET_WRITE_DATELINE)) if _, err := c.Conn.Write(buf.Bytes()); err != nil { if e, ok := err.(net.Error); ok && e.Timeout() { syslog.Info("write timeouat:", err, *c) return nil } syslog.Warn("write to conn fail :", err.Error(), msg.Tail) return errors.As(err) } else { syslog.Debug2("write to conn success:", head, string(msg.BodyData()), msg.Tail) } return nil }
func (h *DBHandler) HandleMessage(message *nsq.Message) error { var resp []byte var err error defer func() { if err != nil { syslog.Warn(err) } }() dataPackage := protocol.GetDataPackage() defer protocol.PutDataPackage(dataPackage) if err := dataPackage.Unpackage(message.Body); err != nil { return nil } head := &dataPackage.Head jsonStr := dataPackage.BodyData() tail := &dataPackage.Tail syslog.Debug(*head, string(jsonStr), *tail) switch head.Command { case protocol.CLIENT_CMD_USER_REGISTER: resp = h.Register(head, jsonStr, tail) case protocol.CLIENT_CMD_USER_LOGIN: resp = h.Login(head, jsonStr, tail) default: syslog.Debug("invalid cmd:", head.Command, *tail) return nil } respBuf := protocol.GetBuffer() defer protocol.PutBuffer(respBuf) head.PkgLen = uint16(protocol.DATA_PACKAGE_HEAD_SIZE + len(resp)) binary.Write(respBuf, binary.BigEndian, head) binary.Write(respBuf, binary.BigEndian, resp) binary.Write(respBuf, binary.BigEndian, tail) topic := fmt.Sprintf("conn_%s_%d", util.IPToStr(tail.IP), tail.Port) common.NsqPublish(topic, respBuf.Bytes()) syslog.Debug2("db_server --> conn_server publish:", topic, head, string(resp), tail) return nil }