Giter VIP home page Giter VIP logo

Comments (1)

CuteReimu avatar CuteReimu commented on May 18, 2024 1

自己实现一下codec那个接口就行了,主要是EncodeDecode函数。下面例子是解析proto,直接调用google的那个proto库。解析json你就换成json.Marshaljson.Unmashal。解析lua你就找个解析lua的第三方库调用一下就行了。

import (
	"github.com/davyxu/cellnet"
	"github.com/davyxu/cellnet/util"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/reflect/protoregistry"
	"reflect"
)

type protoCodec struct {
}

func (c *protoCodec) Name() string {
	return "protobuf" // 随便填
}

func (c *protoCodec) MimeType() string {
	return "application/x-protobuf" // 随便填
}

func (c *protoCodec) Encode(msgObj interface{}, _ cellnet.ContextSet) (data interface{}, err error) {
	// 这里是直接调用protobuf的Marshal函数,如果你想用lua你就换成lua的就行了
	return proto.Marshal(msgObj.(proto.Message))
}

func (c *protoCodec) Decode(data interface{}, msgObj interface{}) error {
	// 这里是直接调用protobuf的UnMarshal函数,如果你想用lua你就换成lua的就行了
	return proto.Unmarshal(data.([]byte), msgObj.(proto.Message))
}

// 将消息注册到系统
func init() {
	c := new(protoCodec)
	// 遍历注册所有协议,想手动指定协议ID就改成自己一个一个写
	protoregistry.GlobalTypes.RangeMessages(func(messageType protoreflect.MessageType) bool {
		cellnet.RegisterMessageMeta(&cellnet.MessageMeta{
			Codec: c,
			Type:  reflect.TypeOf(messageType.Zero().Interface()).Elem(),
			ID:    int(util.StringHash(string(messageType.Descriptor().Name()))),
		})
		return true
	})
}

from cellnet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.