Ejemplo n.º 1
0
func TestExtension(t *testing.T) {
	log.Println("test Extension...")

	request := &Request{}
	proto.SetDefaults(request)
	log.Println("request type:", request.GetType())
	log.Println("request command:", request.GetCommand())
	// has
	log.Println("has extension:",
		proto.HasExtension(request, E_Login_Account))
	// set
	account := &Account{}
	proto.SetDefaults(account)
	account.Name = proto.String("lee")
	account.Token = proto.String("lee")
	log.Println(account.Type, account.GetName(), account.GetToken())

	err := proto.SetExtension(request, E_Login_Account, account)
	if err != nil {
		t.Fatal(err.Error())
	}
	// has
	log.Println("has extension:",
		proto.HasExtension(request, E_Login_Account))
	// get
	var new_account interface{}
	new_account, err = proto.GetExtension(request, E_Login_Account)
	if err != nil {
		t.Fatal(err.Error())
	}
	{
		account := new_account.(*Account)
		log.Println("getname", account.GetName())
	}
	data_type := reflect.TypeOf(new_account)

	log.Println("type:", data_type)
	switch new_account.(type) {
	case *Account:
	default:
		t.Fatal("Bad Type")
	}
	value := reflect.ValueOf(new_account)

	log.Println("value:", value)
	GetName := value.MethodByName("GetName")
	log.Println("is reflect.Func", reflect.Func == GetName.Kind())
	name := GetName.Call(nil)

	name_str := name[0].String()
	log.Println("GetName:", reflect.TypeOf(name_str).Kind())
}
Ejemplo n.º 2
0
func init() {
	netlib.RegisterHandler(int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES), &PacketSlicesHandler{})
	netlib.RegisterFactory(int(protocol.CoreBuiltinPacketID_PACKET_SS_SLICES), &PacketSlicesPacketFactory{})

	netlib.DefaultBuiltinProtocolEncoder.PacketCutor = func(data []byte) (packs []interface{}) {

		var (
			offset    = 0
			sendSize  = 0
			seqNo     = 1
			totalSize = len(data)
			restSize  = len(data)
		)
		for restSize > 0 {
			sendSize = restSize
			if sendSize > netlib.MaxPacketSize-128 {
				sendSize = netlib.MaxPacketSize - 128
			}
			pack := &protocol.SSPacketSlices{
				SeqNo:      proto.Int32(int32(seqNo)),
				TotalSize:  proto.Int32(int32(totalSize)),
				Offset:     proto.Int32(int32(offset)),
				PacketData: data[offset : offset+sendSize],
			}
			proto.SetDefaults(pack)
			seqNo++
			restSize -= sendSize
			offset += sendSize
			packs = append(packs, pack)
		}
		return
	}
}
Ejemplo n.º 3
0
func (this *serviceMgr) OnRegiste(s *netlib.Session) {
	if this == nil || s == nil {
		return
	}

	if s.GetAttribute(SessionAttributeServiceFlag) == nil {
		return
	}
	attr := s.GetAttribute(SessionAttributeServerInfo)
	if attr != nil {
		if srvInfo, ok := attr.(*protocol.SSSrvRegiste); ok && srvInfo != nil {
			services := GetCareServicesBySession(srvInfo.GetType())
			for _, v1 := range services {
				if v2, has := this.servicesPool[v1]; has {
					for _, v3 := range v2 {
						func(si *protocol.ServiceInfo, sInfo *protocol.SSSrvRegiste) {
							pack := &protocol.SSServiceInfo{}
							proto.SetDefaults(pack)
							pack.Service = si
							logger.Trace("serviceMgr.OnRegiste Server Type=", sInfo.GetType(), " Id=", sInfo.GetId(), " Name=", sInfo.GetName(), " careful => Service=", si)
							s.Send(pack)
						}(v3, srvInfo)
					}
				}
			}
		}
	}
}
Ejemplo n.º 4
0
func ConstructTxCmdPacket(tnp *transact.TransNodeParam, cmd transact.TransCmd) proto.Message {
	packet := &protocol.TransactCtrlCmd{
		TId: proto.Int64(int64(tnp.TId)),
		Cmd: proto.Int32(int32(cmd)),
	}
	proto.SetDefaults(packet)
	return packet
}
Ejemplo n.º 5
0
func BenchmarkGetPacketId(b *testing.B) {
	pck := &protocol.SSPacketAuth{AuthKey: proto.String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), Timestamp: proto.Int64(time.Now().Unix())}
	proto.SetDefaults(pck)
	b.StartTimer()
	for i := 0; i < b.N; i++ {
		getPacketId(pck)
	}
	b.StopTimer()
}
Ejemplo n.º 6
0
func (sfl *SessionHandlerSrvRegiste) OnSessionOpened(s *netlib.Session) {
	registePacket := &protocol.SSSrvRegiste{
		Id:     proto.Int(netlib.Config.SrvInfo.Id),
		Type:   proto.Int(netlib.Config.SrvInfo.Type),
		AreaId: proto.Int(netlib.Config.SrvInfo.AreaID),
		Name:   proto.String(netlib.Config.SrvInfo.Name),
	}
	proto.SetDefaults(registePacket)
	s.Send(registePacket)
}
Ejemplo n.º 7
0
func (this *SCPacketPongHandler) Process(session *netlib.Session, data interface{}) error {
	if pong, ok := data.(*protocol.SCPacketPong); ok {
		ping := &protocol.CSPacketPing{
			TimeStamb: proto.Int64(time.Now().Unix()),
			Message:   pong.GetMessage(),
		}
		proto.SetDefaults(ping)
		session.Send(ping)
	}
	return nil
}
Ejemplo n.º 8
0
func (sfcl *SessionHandlerClientLoad) reportLoad(s *netlib.Session) {
	sc := s.GetSessionConfig()
	pack := &protocol.ServerLoad{
		SrvType: proto.Int32(int32(sc.Type)),
		SrvId:   proto.Int32(int32(sc.Id)),
		CurLoad: proto.Int32(int32(srvlib.ClientSessionMgrSington.Count())),
	}
	proto.SetDefaults(pack)
	srvlib.ServerSessionMgrSington.Broadcast(pack, netlib.Config.SrvInfo.AreaID, srvlib.BalanceServerType)
	logger.Tracef("SessionHandlerClientLoad.reportLoad %v", pack)
}
Ejemplo n.º 9
0
func (af *AuthenticationFilter) OnSessionOpened(s *netlib.Session) bool {
	timestamp := time.Now().Unix()
	h := md5.New()
	sc := s.GetSessionConfig()
	h.Write([]byte(fmt.Sprintf("%v;%v", timestamp, sc.AuthKey)))
	authPack := &protocol.SSPacketAuth{
		Timestamp: proto.Int64(timestamp),
		AuthKey:   proto.String(hex.EncodeToString(h.Sum(nil))),
	}
	proto.SetDefaults(authPack)
	s.Send(authPack)
	return true
}
Ejemplo n.º 10
0
func (this *MulticastPacketFactory) CreateMulticastPacket(data interface{}, sis ...*protocol.MCSessionUnion) proto.Message {
	pack := &protocol.SSPacketMulticast{Sessions: sis}
	if byteData, ok := data.([]byte); ok {
		pack.Data = byteData
	} else {
		byteData, err := netlib.MarshalPacket(data)
		if err == nil {
			pack.Data = byteData
		} else {
			logger.Info("MulticastPacketFactory.CreateMulticastPacket err:", err)
		}
	}
	proto.SetDefaults(pack)
	return pack
}
Ejemplo n.º 11
0
func (this *BroadcastPacketFactory) CreateBroadcastPacket(sp *protocol.BCSessionUnion, data interface{}) proto.Message {
	pack := &protocol.SSPacketBroadcast{SessParam: sp}
	if byteData, ok := data.([]byte); ok {
		pack.Data = byteData
	} else {
		byteData, err := netlib.MarshalPacket(data)
		if err == nil {
			pack.Data = byteData
		} else {
			logger.Warn("BroadcastPacketFactory.CreateBroadcastPacket err:", err)
		}
	}
	proto.SetDefaults(pack)
	return pack
}
Ejemplo n.º 12
0
func (this *ProtobufClientManager) GetClient() *ProtobufClient {
	select {
	case c := <-this.clients:
		return c
	default:
		c := &ProtobufClient{
			logger:   this.logger,
			request:  nil,
			response: message.Response{},
			session:  nil,
		}
		// set default response
		proto.SetDefaults(&c.response)
		return c
	}
}
Ejemplo n.º 13
0
func ContructTxResultPacket(parent, me *transact.TransNodeParam, tr *transact.TransResult) proto.Message {
	packet := &protocol.TransactResult{
		MyTId:    proto.Int64(int64(parent.TId)),
		ChildTId: proto.Int64(int64(me.TId)),
		RetCode:  proto.Int32(int32(tr.RetCode)),
	}
	if tr.RetFiels != nil {
		b, err := netlib.MarshalPacketNoPackId(tr.RetFiels)
		if err != nil {
			logger.Info("ContructTxResultPacket Marshal UserData error:", err)
		} else {
			packet.CustomData = b
		}
	}
	proto.SetDefaults(packet)
	return packet
}
Ejemplo n.º 14
0
func (this *serviceMgr) UnregisteService(service *protocol.ServiceInfo) {
	if this == nil || service == nil {
		return
	}

	srvid := service.GetSrvId()
	srvtype := service.GetSrvType()
	if v, has := this.servicesPool[srvtype]; has {
		delete(v, srvid)
	}

	pack := &protocol.SSServiceShut{}
	pack.Service = service
	proto.SetDefaults(pack)
	sessiontypes := GetCareSessionsByService(service.GetSrvType())
	areaId := service.GetAreaId()
	for _, v1 := range sessiontypes {
		ServerSessionMgrSington.Broadcast(pack, int(areaId), int(v1))
	}
}
Ejemplo n.º 15
0
func BenchmarkMarshalPacket(b *testing.B) {
	runtime.GOMAXPROCS(1)

	c, err := net.Dial("tcp", "192.168.1.106:9999")
	if err != nil {
		log.Fatal(err)
	}
	if tcpconn, ok := c.(*net.TCPConn); ok {
		tcpconn.SetLinger(5)
		tcpconn.SetNoDelay(false)
		tcpconn.SetKeepAlive(false)
		tcpconn.SetReadBuffer(102400)
		tcpconn.SetWriteBuffer(10240000)
	}
	sc := &SessionConfig{}
	s := newSession(1, c, sc, nil)

	pck := &protocol.SSPacketAuth{AuthKey: proto.String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), Timestamp: proto.Int64(time.Now().Unix())}
	proto.SetDefaults(pck)
	tNow := time.Now()
	b.StartTimer()

	w := bytes.NewBuffer(nil)

	for i := 0; i < b.N; i++ {
		//for j := 0; j < 100; j++ {
		//	b, err := MarshalPacket(pck)
		//	if err == nil {
		//		binary.Write(w, binary.LittleEndian, b)
		//	}
		//}
		pck2 := &protocol.SSPacketAuth{AuthKey: proto.String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" /*hex.EncodeToString(w.Bytes())*/), Timestamp: proto.Int64(time.Now().Unix())}
		DefaultBuiltinProtocolEncoder.Encode(s, pck2, s.conn)
		w.Reset()
		//Gpb.Marshal(pck)
	}

	b.StopTimer()
	fmt.Println("==========", time.Now().Sub(tNow), "  ==", b.N)
}
Ejemplo n.º 16
0
func (this *Configuration) Init() error {
	this.Connects.Init()
	f := this.Connects.GetFilter(filter.AuthenticationFilterName)
	if f != nil {
		f.(*filter.AuthenticationFilter).SessionAuthHandler = func(s *netlib.Session, bSuc bool) {
			if bSuc {
				packet := &protocol.CSPacketPing{
					TimeStamb: proto.Int64(time.Now().Unix()),
					Message:   []byte("=1234567890abcderghijklmnopqrstuvwxyz="),
				}
				//for i := 0; i < 1024*32; i++ {
				//	packet.Message = append(packet.Message, byte('x'))
				//}
				proto.SetDefaults(packet)
				s.Send(packet)
			} else {
				logger.Info("SessionAuthHandler auth failed")
			}
		}
	}
	return nil
}
Ejemplo n.º 17
0
func (sfcb *SessionHandlerClientBalance) OnSessionOpened(s *netlib.Session) {
	logger.Trace("SessionHandlerClientBalance.OnSessionOpened")
	services := srvlib.ServiceMgr.GetServices(srvlib.ClientServiceType)
	if services != nil {
		/*清理掉线的gate*/
		for k, _ := range sfcb.gates {
			if _, has := services[k]; !has {
				delete(sfcb.gates, k)
			}
		}
		/*补充新上线的gate*/
		for k, v := range services {
			if _, has := sfcb.gates[k]; !has {
				sfcb.gates[k] = &gateService{ServiceInfo: v, active: true}
			}
		}
	}

	/*查找最小负载的gate*/
	var mls *libproto.ServiceInfo
	var min = 100000
	for _, v := range sfcb.gates {
		if v.active && v.load < min {
			mls = v.ServiceInfo
		}
	}
	pack := &protocol.SCGateInfo{}
	if mls != nil {
		pack.SrvType = proto.Int32(mls.GetSrvType())
		pack.SrvId = proto.Int32(mls.GetSrvId())
		pack.AuthKey = proto.String(mls.GetAuthKey())
		pack.Ip = proto.String(mls.GetIp())
		pack.Port = proto.Int32(mls.GetPort())
	}
	proto.SetDefaults(pack)
	s.Send(pack)
	time.AfterFunc(time.Second*5, func() { s.Close() })
}
Ejemplo n.º 18
0
func ContructTxStartPacket(parent, me *transact.TransNodeParam, ud interface{}) proto.Message {
	packet := &protocol.TransactStart{
		MyTNP: &protocol.TransactParam{
			TransNodeID:     proto.Int64(int64(me.TId)),
			TransType:       proto.Int32(int32(me.Tt)),
			OwnerType:       proto.Int32(int32(me.Ot)),
			TransCommitType: proto.Int32(int32(me.Tct)),
			OwnerID:         proto.Int32(int32(me.Oid)),
			SkeletonID:      proto.Int32(int32(me.SkeletonID)),
			LevelNo:         proto.Int32(int32(me.LevelNo)),
			AreaID:          proto.Int32(int32(me.AreaID)),
			TimeOut:         proto.Int64(int64(me.TimeOut)),
		},
		ParenTNP: &protocol.TransactParam{
			TransNodeID:     proto.Int64(int64(parent.TId)),
			TransType:       proto.Int32(int32(parent.Tt)),
			OwnerType:       proto.Int32(int32(parent.Ot)),
			TransCommitType: proto.Int32(int32(parent.Tct)),
			OwnerID:         proto.Int32(int32(parent.Oid)),
			SkeletonID:      proto.Int32(int32(parent.SkeletonID)),
			LevelNo:         proto.Int32(int32(parent.LevelNo)),
			AreaID:          proto.Int32(int32(parent.AreaID)),
			TimeOut:         proto.Int64(int64(parent.TimeOut)),
		},
	}

	if ud != nil {
		b, err := netlib.MarshalPacketNoPackId(ud)
		if err != nil {
			logger.Info("ContructTxStartPacket Marshal UserData error:", err)
		} else {
			packet.CustomData = b
		}
	}
	proto.SetDefaults(packet)
	return packet
}
Ejemplo n.º 19
0
func (this *Client) ping() bool {
	var n int
	request := &message.Request{}
	proto.SetDefaults(request)
	message, err := proto.Marshal(request)
	if err != nil {
		log.Println(err)
		return false
	}
	//size := proto.Size(request)
	size := len(message)
	log.Println("sending header...")
	//
	this.wheader.SetSize(uint32(size))
	log.Println(this.wheader)
	//
	n, err = this.writer.Write(this.wheader[:])
	if err != nil || n != len(this.wheader) {
		log.Println(err.Error())
		return false
	}
	log.Println(n, "bytes sent")
	//
	log.Println("sending message...")
	n, err = this.writer.Write(message)
	if err != nil || n != size {
		log.Println(err.Error())
		return false
	}
	log.Println(n, "bytes sent")
	err = this.writer.Flush()
	if err != nil {
		log.Println(err.Error())
		return false
	}
	return true
}
Ejemplo n.º 20
0
func (this *serviceMgr) RegisteService(s *netlib.Session, services []*protocol.ServiceInfo) {
	if this == nil || services == nil || len(services) == 0 {
		return
	}

	s.SetAttribute(SessionAttributeServiceInfo, services)
	for _, service := range services {
		srvid := service.GetSrvId()
		srvtype := service.GetSrvType()
		if _, has := this.servicesPool[srvtype]; !has {
			this.servicesPool[srvtype] = make(map[int32]*protocol.ServiceInfo)
		}
		this.servicesPool[srvtype][srvid] = service

		pack := &protocol.SSServiceInfo{}
		pack.Service = service
		proto.SetDefaults(pack)
		sessiontypes := GetCareSessionsByService(service.GetSrvType())
		areaId := service.GetAreaId()
		for _, v1 := range sessiontypes {
			ServerSessionMgrSington.Broadcast(pack, int(areaId), int(v1))
		}
	}
}
Ejemplo n.º 21
0
func (kf *KeepAliveFilter) OnSessionIdle(s *netlib.Session) bool {
	p := &protocol.SSPacketKeepAlive{Flag: proto.Int32(0)}
	proto.SetDefaults(p)
	s.Send(p)
	return true
}
Ejemplo n.º 22
0
func (this *serviceMgr) ReportService(s *netlib.Session) {
	acceptors := netlib.GetAcceptors()
	cnt := len(acceptors)
	if cnt > 0 {
		pack := &protocol.SSServiceRegiste{
			Services: make([]*protocol.ServiceInfo, 0, cnt),
		}
		proto.SetDefaults(pack)
		for _, v := range acceptors {
			addr := v.Addr()
			if addr == nil {
				continue
			}
			network := addr.Network()
			s := addr.String()
			ipAndPort := strings.Split(s, ":")
			if len(ipAndPort) < 2 {
				continue
			}

			port, err := strconv.Atoi(ipAndPort[len(ipAndPort)-1])
			if err != nil {
				continue
			}

			sc := v.GetSessionConfig()
			si := &protocol.ServiceInfo{
				AreaId:          proto.Int32(int32(sc.AreaId)),
				SrvId:           proto.Int32(int32(sc.Id)),
				SrvType:         proto.Int32(int32(sc.Type)),
				SrvPID:          proto.Int32(int32(os.Getpid())),
				SrvName:         proto.String(sc.Name),
				NetworkType:     proto.String(network),
				Ip:              proto.String(sc.Ip),
				Port:            proto.Int32(int32(port)),
				WriteTimeOut:    proto.Int32(int32(sc.WriteTimeout / time.Second)),
				ReadTimeOut:     proto.Int32(int32(sc.ReadTimeout / time.Second)),
				IdleTimeOut:     proto.Int32(int32(sc.IdleTimeout / time.Second)),
				MaxDone:         proto.Int32(int32(sc.MaxDone)),
				MaxPend:         proto.Int32(int32(sc.MaxPend)),
				MaxPacket:       proto.Int32(int32(sc.MaxPacket)),
				RcvBuff:         proto.Int32(int32(sc.RcvBuff)),
				SndBuff:         proto.Int32(int32(sc.SndBuff)),
				SoLinger:        proto.Int32(int32(sc.SoLinger)),
				KeepAlive:       proto.Bool(sc.KeepAlive),
				NoDelay:         proto.Bool(sc.NoDelay),
				IsAutoReconn:    proto.Bool(sc.IsAutoReconn),
				IsInnerLink:     proto.Bool(sc.IsInnerLink),
				SupportFragment: proto.Bool(sc.SupportFragment),
				AllowMultiConn:  proto.Bool(sc.AllowMultiConn),
				AuthKey:         proto.String(sc.AuthKey),
				EncoderName:     proto.String(sc.EncoderName),
				DecoderName:     proto.String(sc.DecoderName),
				FilterChain:     sc.FilterChain,
				HandlerChain:    sc.HandlerChain,
				Protocol:        proto.String(sc.Protocol),
				Path:            proto.String(sc.Path),
			}
			pack.Services = append(pack.Services, si)
		}
		s.Send(pack)
	}
}