Beispiel #1
0
func (h *DBHandler) Login(head *protocol.PackageHead, jsonBody []byte, tail *protocol.PackageTail) (result []byte) {
	var req protocol.LoginRequest
	var rsp protocol.LoginResponse
	errCode := 0
	var err error = nil

	defer func() {
		rsp.ErrorCode = proto.Uint32(uint32(errCode))
		syslog.Debug(rsp.String())
		result, err = proto.Marshal(&rsp)
		if err != nil {
			syslog.Debug(err)
		}
	}()

	if err := proto.Unmarshal(jsonBody, &req); err != nil {
		errCode = errors.Code(errors.CLIENT_ERR_UNKNOW_ERROR)
		return
	}

	phonenum := req.GetUsername()
	password := req.GetPassword()

	userInfo, _ := user.GetUserInfoByPhoneNum(phonenum)
	if userInfo == nil {
		errCode = errors.Code(errors.CLIENT_ERR_USER_NOT_EXIST)
		return
	}

	if userInfo.Password != password {
		errCode = errors.Code(errors.CLIENT_ERR_PASSWORD_ERROR)
		return
	}

	us, err := user.GetUserState(userInfo.Uid)
	if err != nil {
		syslog.Info("GetUserState failed!!!", err)
	}
	us.Uid = userInfo.Uid
	us.Sid = tail.SID
	us.ConnIP = tail.IP
	us.ConnPort = tail.Port
	//us.SetupId = req.SetupId
	us.Online = true
	if err := user.SetUserState(us); err != nil {
		syslog.Info("SetUserState failed", us)
	}

	rsp.UserId = proto.Uint64(userInfo.Uid)
	tail.UID = userInfo.Uid
	return
}
Beispiel #2
0
func (h *DBHandler) Register(head *protocol.PackageHead, jsonBody []byte, tail *protocol.PackageTail) (result []byte) {
	var req protocol.RegisterRequest
	var rsp protocol.RegisterResponse
	errCode := 0
	var err error = nil

	defer func() {
		rsp.ErrorCode = proto.Uint32(uint32(errCode))
		syslog.Debug(rsp.String())
		result, err = proto.Marshal(&rsp)
		if err != nil {
			syslog.Debug(err)
		}
	}()

	if err := proto.Unmarshal(jsonBody, &req); err != nil {
		errCode = errors.Code(errors.CLIENT_ERR_UNKNOW_ERROR)
		return
	}

	phonenum := req.GetUsername()
	password := req.GetPassword()

	userInfo, _ := user.GetUserInfoByPhoneNum(phonenum)
	if userInfo != nil {
		errCode = errors.Code(errors.CLIENT_ERR_USER_EXIST)
		return
	}

	userInfo = &user.UserInfo{
		Password: password,
		PhoneNum: phonenum,
	}

	if err := user.SaveUserInfo(userInfo); err != nil {
		errCode = errors.Code(errors.CLIENT_ERR_UNKNOW_ERROR)
		return
	}

	rsp.UserId = proto.Uint64(userInfo.Uid)
	tail.UID = userInfo.Uid
	return
}
Beispiel #3
0
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
}
Beispiel #4
0
func (c *Client) Produce(msg *protocol.DataPackage) error {
	head := msg.Head
	buf := protocol.GetBuffer()
	defer protocol.PutBuffer(buf)
	if err := msg.Package(buf); err != nil {
		return errors.As(err)
	}

	if head.Command == protocol.CLIENT_CMD_SEND_USER_MSG || head.Command == protocol.CLIENT_CMD_RECV_USER_MSG {
		if err := common.NsqPublish(common.MSG_SERVER_TOPIC, buf.Bytes()); err != nil {
			return errors.As(err)
		}
		syslog.Debug("gateway --> msg_server publish message:", head, msg.Tail)
	} else if head.Command == protocol.CLIENT_CMD_USER_LOGIN || head.Command == protocol.CLIENT_CMD_USER_REGISTER {
		if err := common.NsqPublish(common.USER_CENTER_TOPIC, buf.Bytes()); err != nil {
			return errors.As(err)
		}
		syslog.Debug("gateway --> user_center publish message:", head, msg.Tail)
	}
	return nil
}
Beispiel #5
0
func (this *Service) Serve() {
	this.WaitGroup.AddOne()
	defer this.WaitGroup.Done()
	exitNotify := this.WaitGroup.ExitNotify()
	var grpCount int32 = 0
	var clientCount int32 = 0
	var sid uint32 = 10000
	for {
		select {
		case <-exitNotify:
			return
		default:
		}

		this.Listener.SetDeadline(time.Now().Add(NET_READ_DATELINE))
		conn, err := this.Listener.AcceptTCP()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			syslog.Warn("Unknow Net Error:", err)
			break
		}
		syslog.Debug(conn.RemoteAddr(), "connected, seesionId:", sid)
		// 建立客户端
		client := GetClient()
		client.Service = this
		client.Conn = conn
		client.Sid = sid
		client.Stat = CLIENT_STATE_INIT
		client.RespCh = nil
		client.MsgCount = 0
		client.LastTime = time.Now().Unix()
		this.RWMutex.Lock()
		this.ClientMap[sid] = client
		this.RWMutex.Unlock()
		this.ClientCh <- client
		clientCount = atomic.AddInt32(&this.ClientCount, 1)

		grpCount = atomic.LoadInt32(&this.ClientGroupCount)
		if clientCount >= ((grpCount - 10) * CLIENT_NUM_PER_GROUP) {
			NewClientGroup(this)
		}
		// 处理客户端请求
		sid++ // increase sid
	}
}
Beispiel #6
0
func (h *Handler) HandleMessage(message *nsq.Message) error {
	dataPackage := common.GetDataPackage()
	defer common.PutDataPackage(dataPackage)
	if err := dataPackage.Unpackage(message.Body); err != nil {
		syslog.Warn(err)
		return nil
	}

	head := &dataPackage.Head
	jsonStr := dataPackage.BodyData()
	tail := &dataPackage.Tail

	switch head.Command {
	case common.XXX_CMD_SEND_USER_MSG:
	default:
		syslog.Warn("Invalid Cmd :", head.Command, *tail)
	}
	// get user state
	us, err := user.GetUserState(tail.UID)
	if err != nil {
		syslog.Info("GetUserState failed!!!", tail)
		return nil
	}
	// not online
	if us.Online == false {
		syslog.Debug("client not online!!! uid:", tail.UID)
		return nil
	}

	tail.IP = us.ConnIP
	tail.Port = us.ConnPort
	tail.SID = us.Sid
	tail.UID = us.Uid

	respBuf := common.GetBuffer()
	defer common.PutBuffer(respBuf)
	if err := common.Package(respBuf, head, jsonStr, tail); err != nil {
		syslog.Info(err)
		return nil
	}
	topic := fmt.Sprintf("conn_%s_%d", util.IPToStr(tail.IP), tail.Port)
	common.NsqPublish(topic, respBuf.Bytes())
	return nil
}
Beispiel #7
0
func (c *Client) Stop() {
	if 0 < atomic.LoadInt32(&c.MsgCount) {
		time.AfterFunc(time.Second*30, c.Stop)
		return
	}
	syslog.Debug("client ", c.Uid, "Sid ", c.Sid, " disconnect!!", c.Conn.RemoteAddr())
	c.Conn.Close()
	us, err := user.GetUserState(c.Uid)
	if err != nil {
		syslog.Info("GetUserState failed!!!", err)
	}
	if us.Uid == c.Uid && us.Sid == c.Sid {
		if err := user.SetUserState(&user.UserState{Uid: c.Uid}); err != nil {
			syslog.Info("SetUserState failed!!!", err)
		}
	}
	c.Stat = CLIENT_STATE_OFFLINE
	c.Service.RWMutex.Lock()
	delete(c.Service.ClientMap, c.Sid)
	c.Service.RWMutex.Unlock()
	atomic.AddInt32(&c.Service.ClientCount, -1)
	PutClient(c)
}
Beispiel #8
0
func (this *Service) P2pService(sock *net.UDPConn) {
	this.WaitGroup.AddOne()
	defer this.WaitGroup.Done()
	exitNotify := this.WaitGroup.ExitNotify()
	var buf [2048]byte
	for {
		select {
		case <-exitNotify:
			return
		default:
		}
		sock.SetDeadline(time.Now().Add(NET_READ_MAX_DATELINE))
		n, addr, err := sock.ReadFromUDP(buf[:])
		if err != nil {
			syslog.Info(err)
			continue
		}
		if n < 4 {
			syslog.Info("udp data package too small")
			continue
		}
		sid := binary.BigEndian.Uint32(buf[:4])
		this.RWMutex.RLock()
		client, ok := this.ClientMap[sid]
		this.RWMutex.RUnlock()
		if ok == false {
			syslog.Debug("client not exist!!! sid:", sid)
			continue
		}
		client.IP = util.IPToInt(addr.String())
		client.Port = uint32(addr.Port)
		if _, err := sock.WriteToUDP([]byte(addr.String()), addr); err != nil {
			syslog.Info("udp send data failed!!!", err)
			continue
		}
	}
}
Beispiel #9
0
func (c *Client) Request() bool {
	var reqBuf [2048]byte
	curTime := time.Now().Unix()
	c.Conn.SetDeadline(time.Now().Add(NET_READ_DATELINE))
	if _, err := io.ReadFull(c.Conn, reqBuf[:2]); err != nil {
		if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
			// 太长时间没有交互退出
			if c.Stat == CLIENT_STATE_INIT && c.LastTime+CONNECT_NO_LOGIN_TIMEOUT < curTime {
				syslog.Info(c.Uid, c.Sid, "no login timeout 30 s, lastTime:", c.LastTime, " nowTime:", curTime)
				return false
			} else if c.LastTime+CONNECT_NO_REQUEST_TIMEOUT < curTime {
				syslog.Info(c.Uid, c.Sid, "timeout 180 s, lastTime:", c.LastTime, " nowTime:", curTime)
				return false
			}
			return true
		}
		syslog.Info(c.Uid, c.Sid, "recv error:", err.Error())
		return false
	} else {
		headLen := binary.BigEndian.Uint16(reqBuf[0:2])
		if headLen > protocol.DATA_PACKAGE_MAX_SIZE {
			syslog.Info(c.Uid, c.Sid, "head len :", headLen, " too large", reqBuf[0], reqBuf[1])
			return true
		} else if headLen < protocol.DATA_PACKAGE_HEAD_SIZE {
			syslog.Info(c.Uid, c.Sid, "head len :", headLen, " too small", reqBuf[0], reqBuf[1])
			return true
		}
		c.Conn.SetDeadline(time.Now().Add(NET_READ_MAX_DATELINE))
		if _, err := io.ReadFull(c.Conn, reqBuf[2:headLen]); err != nil {
			syslog.Info(c.Uid, c.Sid, "recv error:", err)
			return false
		}
		dataPackage := protocol.GetDataPackage()
		defer protocol.PutDataPackage(dataPackage)
		if err := dataPackage.Unpackage(reqBuf[:headLen]); err != nil {
			syslog.Info(c.Uid, c.Sid, "DecPkgBody failed :", err)
			return false
		}
		head := dataPackage.Head
		syslog.Debug("client requst:", head)
		if head.Command != protocol.CLIENT_CMD_HEARTBEAT && head.Command != protocol.CLIENT_CMD_USER_LOGIN &&
			head.Command != protocol.CLIENT_CMD_USER_REGISTER && c.Stat != CLIENT_STATE_ONLINE {
			syslog.Info("no login no operate!!!", head)
			return false
		} else {
			c.LastTime = time.Now().Unix()
			dataPackage.Tail.IP = g_IP
			dataPackage.Tail.Port = g_Port
			dataPackage.Tail.SID = c.Sid
			dataPackage.Tail.UID = c.Uid
			dataPackage.Data = c
			if head.Command != protocol.CLIENT_CMD_HEARTBEAT {
				//派发消息到其它服务器处理
				err = c.Produce(dataPackage)
			} else {
				//回复心跳
				err = c.Response(dataPackage)
			}
			if err != nil {
				syslog.Info(err)
				return false
			}
		}
	}
	return true
}