Example #1
0
func (p *protocolV1) SayHi(client *clientV1, body []byte) (int32, []byte, error) {
	if len(body) <= 0 {
		return 0, nil, protocol.NewClientErr(nil, "E_INVALID", fmt.Sprintf("invalid message body size %d in sayhi", len(body)))
	}

	sayHiReq := &onepiece.SayHiRequest{}
	err := proto.Unmarshal(body, sayHiReq)
	if err != nil {
		return 0, nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid unmarshaling err in sayhi"))

	}

	if sayHiReq.Msg != "hi" {
		return 0, nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid message body content in sayhi"))
	}

	sayHiRes := &onepiece.SayHiResponse{
		Msg: "叔叔不约!",
	}

	buffer, err := proto.Marshal(sayHiRes)
	if err != nil {
		return 0, nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid marshaling err in sayhi"))
	}

	return int32(onepiece.NetMsgID_SAYHI), buffer, nil
}
Example #2
0
func (p *protocolV1) Exec(client *clientV1) (int32, []byte, error) {
	bodyLen, err := readLen(client.Reader, client.lenSlice)
	if err != nil {
		if err == io.EOF {
			return 0, nil, nil
		}
		return 0, nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("failed to read message body size %s", err))
	}

	// body 必须包含4个字节的消息ID
	if bodyLen < 4 {
		return 0, nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid message body size %d", bodyLen))
	}

	fullContent := make([]byte, bodyLen)

	_, err = io.ReadFull(client.Reader, fullContent)
	if err != nil {
		return 0, nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid message body size %d", len(fullContent)))
	}

	msgid := binary.BigEndian.Uint32(fullContent[:4])
	msgBody := fullContent[4:]

	switch onepiece.NetMsgID(msgid) {
	case onepiece.NetMsgID_SAYHI:
		return p.SayHi(client, msgBody)
	case onepiece.NetMsgID_HEART_BEAT:
		return p.HeartBeat(client, msgBody)
	case onepiece.NetMsgID_REGISTER:
		return p.Register(client, msgBody)
	case onepiece.NetMsgID_AUTO_REGISTER:
		return p.AutoRegister(client, msgBody)
	case onepiece.NetMsgID_LOGIN:
		return p.Login(client, msgBody)
	case onepiece.NetMsgID_LOGIN_WORLD:
		return p.LoginWorld(client, msgBody)
	case onepiece.NetMsgID_RANDOM_ROLE_NAME:
		return p.RandomRoleName(client, msgBody)
	case onepiece.NetMsgID_CREATE_ROLE:
		return p.CreateRole(client, msgBody)
	case onepiece.NetMsgID_DELETE_ROLE:
		return p.DeleteRole(client, msgBody)
	case onepiece.NetMsgID_CHOOSE_ROLE:
		return p.ChooseRole(client, msgBody)
	}

	return 0, nil, protocol.NewFatalClientErr(nil, "E_INVALID", fmt.Sprintf("invalid command by netmessageid %d", msgid))

}