// Insert can insert record into a btree func (t *Btree) insert(record TreeLog) error { tnode, err := t.getTreeNode(t.GetRoot()) if err != nil { if err.Error() != "no data" { return err } nnode := t.newTreeNode() nnode.NodeType = proto.Int32(isLeaf) _, err = nnode.insertRecord(record, t) if err == nil { t.Nodes[nnode.GetId()], err = proto.Marshal(nnode) } t.Root = proto.Int64(nnode.GetId()) return err } clonednode, err := tnode.insertRecord(record, t) if err == nil && len(clonednode.GetKeys()) > int(t.GetNodeMax()) { nnode := t.newTreeNode() nnode.NodeType = proto.Int32(isNode) key, left, right := clonednode.split(t) nnode.insertOnce(key, left, right, t) t.Nodes[nnode.GetId()], err = proto.Marshal(nnode) t.Root = proto.Int64(nnode.GetId()) } else { t.Root = proto.Int64(clonednode.GetId()) } return err }
func TestParseSectionIntro_Valid(t *testing.T) { lines := []string{ "10", "BUILDID", "NODEID 123 321 789", "12 23 34", } trace := Trace{} err := parseSectionIntro(lines, &trace) if err != nil { t.Fatal("Unexpected error:", err) } expectedTrace := Trace{ FileFormatVersion: proto.Int32(10), BuildId: proto.String("BUILDID"), NodeId: proto.String("NODEID"), ProcessStartTimeMicroseconds: proto.Int64(123), SequenceNumber: proto.Int32(321), TraceCreationTimestamp: proto.Int64(789), PcapReceived: proto.Uint32(12), PcapDropped: proto.Uint32(23), InterfaceDropped: proto.Uint32(34), } checkProtosEqual(t, &expectedTrace, &trace) }
func NewTimestampDatum(key string, timestamp int64, t time.Time) ( d pb.TelemetryDatum) { d.Key = proto.String(key) d.Timestamp = proto.Int64(timestamp) d.UnixTimestamp = proto.Int64(t.Unix()) return d }
func TestRunBroadcastFive(t *testing.T) { c := make(chan Packet, 100) var r run r.seqn = 1 r.out = c r.addr = []*net.UDPAddr{ MustResolveUDPAddr("udp", "1.2.3.4:5"), MustResolveUDPAddr("udp", "2.3.4.5:6"), MustResolveUDPAddr("udp", "3.4.5.6:7"), MustResolveUDPAddr("udp", "4.5.6.7:8"), MustResolveUDPAddr("udp", "5.6.7.8:9"), } r.broadcast(newInvite(1)) c <- Packet{} exp := msg{ Seqn: proto.Int64(1), Cmd: invite, Crnd: proto.Int64(1), } addr := make([]*net.UDPAddr, len(r.addr)) for i := 0; i < len(r.addr); i++ { p := <-c addr[i] = p.Addr var got msg err := proto.Unmarshal(p.Data, &got) assert.Equal(t, nil, err) assert.Equal(t, exp, got) } assert.Equal(t, Packet{}, <-c) assert.Equal(t, r.addr, addr) }
func TestParseSectionPacketSeries_Valid(t *testing.T) { lines := []string{ "10 11", "0 10 23", "20 12 45", "10 10 20", } trace := Trace{} err := parseSectionPacketSeries(lines, &trace) if err != nil { t.Fatal("Unexpected error:", err) } expectedTrace := Trace{ PacketSeriesDropped: proto.Uint32(11), PacketSeries: []*PacketSeriesEntry{ &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(10), Size: proto.Int32(10), FlowId: proto.Int32(23), }, &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(30), Size: proto.Int32(12), FlowId: proto.Int32(45), }, &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(40), Size: proto.Int32(10), FlowId: proto.Int32(20), }, }, } checkProtosEqual(t, &expectedTrace, &trace) }
// UpdateBatch implements HighWatermarker. func (w *LevelDBHighWatermarker) UpdateBatch(m FingerprintHighWatermarkMapping) error { batch := leveldb.NewBatch() defer batch.Close() for fp, t := range m { existing, present, err := w.Get(&fp) if err != nil { return err } k := &dto.Fingerprint{} dumpFingerprint(k, &fp) v := &dto.MetricHighWatermark{} if !present { v.Timestamp = proto.Int64(t.Unix()) batch.Put(k, v) continue } // BUG(matt): Replace this with watermark management. if t.After(existing) { v.Timestamp = proto.Int64(t.Unix()) batch.Put(k, v) } } return w.LevelDBPersistence.Commit(batch) }
func TestRunBroadcastFive(t *testing.T) { c := make(chan Packet, 100) var r run r.seqn = 1 r.out = c r.addr = []*net.UDPAddr{ &net.UDPAddr{net.IP{1, 2, 3, 4}, 5}, &net.UDPAddr{net.IP{2, 3, 4, 5}, 6}, &net.UDPAddr{net.IP{3, 4, 5, 6}, 7}, &net.UDPAddr{net.IP{4, 5, 6, 7}, 8}, &net.UDPAddr{net.IP{5, 6, 7, 8}, 9}, } r.broadcast(newInvite(1)) c <- Packet{} exp := msg{ Seqn: proto.Int64(1), Cmd: invite, Crnd: proto.Int64(1), } addr := make([]*net.UDPAddr, len(r.addr)) for i := 0; i < len(r.addr); i++ { p := <-c addr[i] = p.Addr var got msg err := proto.Unmarshal(p.Data, &got) assert.Equal(t, nil, err) assert.Equal(t, exp, got) } assert.Equal(t, Packet{}, <-c) assert.Equal(t, r.addr, addr) }
func (p *Actor) OnReceive(uid interface{}, data []byte) { m, err := kodec.Unboxing(data) if err != nil { log.Println("decode err ", err) return } switch v := m.(type) { case *kodec.Msg: v.From = proto.Int64(int64(uid.(int))) v.Ct = proto.Int64(tick()) if v.GetTp() != kodec.Msg_SYS { from := int(v.GetFrom()) to := v.GetTo() if !p.checker.CheckUp(from, to) { log.Println(fmt.Errorf("warning: chat not allow, %d -> %v \n", from, to)) return } } p.dispatchMsg(v) default: log.Println(fmt.Errorf("unknown data frame")) } }
func (g *Gossiper) scuttlebutt(id string, reqd []*Digest) ([]*Digest, []*Delta) { digests := make([]*Digest, 0) deltas := make([]*Delta, 0) for _, d := range reqd { p := g.peers[d.GetId()] if p == nil { digests = append(digests, &Digest{ Id: proto.String(d.GetId()), Gen: proto.Int64(0), Version: proto.Int64(0), }) } else { cr := p.compare(d.GetGen(), d.GetVersion()) switch { case cr > 0: deltas = append(deltas, g.deltaAfterVersion(p, d.GetVersion())) case cr < 0: digests = append(digests, &Digest{ Id: proto.String(p.id), Gen: proto.Int64(p.gen), Version: proto.Int64(p.version), }) } } } return digests, deltas }
func BenchmarkRegressionSplitter(b *testing.B) { flag.Parse() forestConfig := &pb.ForestConfig{ NumWeakLearners: proto.Int64(int64(*numTrees)), SplittingConstraints: &pb.SplittingConstraints{ MaximumLevels: proto.Int64(int64(*numLevels)), }, LossFunctionConfig: &pb.LossFunctionConfig{ LossFunction: pb.LossFunction_LOGIT.Enum(), }, Algorithm: pb.Algorithm_BOOSTING.Enum(), } glog.Info(forestConfig.String()) generator, err := NewForestGenerator(forestConfig) if err != nil { glog.Fatal(err) } examples := constructBenchmarkExamples(b.N, *numFeatures, 0) glog.Infof("Starting with %v examples", len(examples)) b.ResetTimer() forest := generator.ConstructForest(examples) res, err := json.MarshalIndent(forest, "", " ") if err != nil { glog.Fatalf("Error: %v", err) } glog.Info(res) }
func ExampleBytesPerDevice_multipleSessions() { trace1 := Trace{ PacketSeries: []*PacketSeriesEntry{ &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(0), Size: proto.Int32(10), FlowId: proto.Int32(4), }, }, FlowTableEntry: []*FlowTableEntry{ &FlowTableEntry{ FlowId: proto.Int32(4), SourceIp: proto.String("1.2.3.4"), }, }, AddressTableEntry: []*AddressTableEntry{ &AddressTableEntry{ IpAddress: proto.String("1.2.3.4"), MacAddress: proto.String("AABBCCDDEEFF"), }, }, } trace2 := Trace{ PacketSeries: []*PacketSeriesEntry{ &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(0), Size: proto.Int32(13), FlowId: proto.Int32(4), }, }, } trace3 := Trace{ PacketSeries: []*PacketSeriesEntry{ &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(0), Size: proto.Int32(20), FlowId: proto.Int32(4), }, }, } consistentRanges := []*store.Record{ &store.Record{ Key: lex.EncodeOrDie("node0", "anon0", int64(0), int32(0)), Value: lex.EncodeOrDie("node0", "anon0", int64(0), int32(2)), }, } firstRecords := map[string]Trace{ string(lex.EncodeOrDie("node0", "anon0", int64(0), int32(0))): trace1, } secondRecords := map[string]Trace{ string(lex.EncodeOrDie("node0", "anon0", int64(0), int32(1))): trace2, string(lex.EncodeOrDie("node0", "anon0", int64(0), int32(2))): trace3, } runBytesPerDevicePipeline(consistentRanges, firstRecords, secondRecords) // Output: // node0,AABBCCDDEEFF,0: 43 }
func ExampleBytesPerDevice_macBoundAtStartOfFlow() { trace1 := Trace{ PacketSeries: []*PacketSeriesEntry{ &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(0), Size: proto.Int32(10), FlowId: proto.Int32(4), }, }, FlowTableEntry: []*FlowTableEntry{ &FlowTableEntry{ FlowId: proto.Int32(4), SourceIp: proto.String("1.2.3.4"), DestinationIp: proto.String("4.3.2.1"), }, }, AddressTableEntry: []*AddressTableEntry{ &AddressTableEntry{ IpAddress: proto.String("1.2.3.4"), MacAddress: proto.String("AABBCCDDEEFF"), }, }, } trace2 := Trace{ PacketSeries: []*PacketSeriesEntry{ &PacketSeriesEntry{ TimestampMicroseconds: proto.Int64(0), Size: proto.Int32(12), FlowId: proto.Int32(4), }, }, AddressTableEntry: []*AddressTableEntry{ &AddressTableEntry{ IpAddress: proto.String("1.2.3.4"), MacAddress: proto.String("FFEEDDCCBBAA"), }, }, } consistentRanges := []*store.Record{ &store.Record{ Key: lex.EncodeOrDie("node0", "anon0", int64(0), int32(0)), Value: lex.EncodeOrDie("node0", "anon0", int64(0), int32(1)), }, } records := map[string]Trace{ string(lex.EncodeOrDie("node0", "anon0", int64(0), int32(0))): trace1, string(lex.EncodeOrDie("node0", "anon0", int64(0), int32(1))): trace2, } runBytesPerDevicePipeline(consistentRanges, records) // Output: // node0,AABBCCDDEEFF,0: 22 }
func (c curationState) Get() (key, value coding.Encoder) { key = coding.NewProtocolBuffer(&dto.CurationKey{ Fingerprint: model.NewFingerprintFromRowKey(c.fingerprint).ToDTO(), MinimumGroupSize: proto.Uint32(uint32(c.groupSize)), OlderThan: proto.Int64(int64(c.recencyThreshold)), }) value = coding.NewProtocolBuffer(&dto.CurationValue{ LastCompletionTimestamp: proto.Int64(c.lastCurated.Unix()), }) return }
func createmessage() []byte { ProtoMessage := new(msgproto.Msg) ProtoMessage.Id = proto.Int32(12344) ProtoMessage.Lat = proto.Int64(12344) ProtoMessage.Long = proto.Int64(12344) ProtoMessage.Utime = proto.Int64(int64(time.Now().Unix())) data, err := proto.Marshal(ProtoMessage) if err != nil { fmt.Println(err) } return data }
func runAvailabilityPipelineAugmented(startTimestamp int64, timestamps map[string]int64, moreTimestamps map[string]int64) { levelDbManager := store.NewSliceManager() tracesStore := levelDbManager.Writer("traces") tracesStore.BeginWriting() for encodedKey, timestamp := range timestamps { trace := Trace{ TraceCreationTimestamp: proto.Int64(timestamp), } encodedTrace, err := proto.Marshal(&trace) if err != nil { panic(fmt.Errorf("Error encoding protocol buffer: %v", err)) } tracesStore.WriteRecord(&store.Record{Key: []byte(encodedKey), Value: encodedTrace}) } tracesStore.EndWriting() writer := bytes.NewBuffer([]byte{}) transformer.RunPipeline(AvailabilityPipeline(levelDbManager, writer, startTimestamp)) tracesStore.BeginWriting() for encodedKey, timestamp := range moreTimestamps { trace := Trace{ TraceCreationTimestamp: proto.Int64(timestamp), } encodedTrace, err := proto.Marshal(&trace) if err != nil { panic(fmt.Errorf("Error encoding protocol buffer: %v", err)) } tracesStore.WriteRecord(&store.Record{Key: []byte(encodedKey), Value: encodedTrace}) } tracesStore.EndWriting() anotherTracesSlice := make([]*store.Record, 0) for encodedKey, timestamp := range moreTimestamps { trace := Trace{ TraceCreationTimestamp: proto.Int64(timestamp), } encodedTrace, err := proto.Marshal(&trace) if err != nil { panic(fmt.Errorf("Error encoding protocol buffer: %v", err)) } anotherTracesSlice = append(anotherTracesSlice, &store.Record{Key: []byte(encodedKey), Value: encodedTrace}) } anotherWriter := bytes.NewBuffer([]byte{}) transformer.RunPipeline(AvailabilityPipeline(levelDbManager, anotherWriter, startTimestamp)) fmt.Printf("%s", anotherWriter.Bytes()) }
func (m *MyCalcService) Divide(req *CalcRequest, resp *CalcResponse) (err error) { resp.Result = proto.Int64(0) defer func() { if x := recover(); x != nil { if ex, ok := x.(error); ok { err = ex } else { err = errors.New(fmt.Sprint(x)) } } }() resp.Result = proto.Int64((*req.A) / (*req.B)) resp.Remainder = proto.Int64((*req.A) % (*req.B)) return }
func (project *Project) CreateEntryWithDuration( content string, duration time.Duration, billable bool) *Entry { e := project.CreateEntry(content, billable) endTime := time.Now() startTime := endTime.Add(-duration) e.Started = proto.Int64(startTime.Unix()) e.Ended = proto.Int64(endTime.Unix()) e.Duration = proto.Int64(duration.Nanoseconds()) return e }
func eventToPbEvent(event *Event) (*proto.Event, error) { var e proto.Event if event.Host == "" { event.Host, _ = os.Hostname() } t := reflect.ValueOf(&e).Elem() s := reflect.ValueOf(event).Elem() typeOfEvent := s.Type() for i := 0; i < s.NumField(); i++ { f := s.Field(i) value := reflect.ValueOf(f.Interface()) if reflect.Zero(f.Type()) != value && f.Interface() != nil { name := typeOfEvent.Field(i).Name switch name { case "State", "Service", "Host", "Description": tmp := reflect.ValueOf(pb.String(value.String())) t.FieldByName(name).Set(tmp) case "Ttl": tmp := reflect.ValueOf(pb.Float32(float32(value.Float()))) t.FieldByName(name).Set(tmp) case "Time": tmp := reflect.ValueOf(pb.Int64(value.Int())) t.FieldByName(name).Set(tmp) case "Tags": tmp := reflect.ValueOf(value.Interface().([]string)) t.FieldByName(name).Set(tmp) case "Metric": switch reflect.TypeOf(f.Interface()).Kind() { case reflect.Int: tmp := reflect.ValueOf(pb.Int64(int64(value.Int()))) t.FieldByName("MetricSint64").Set(tmp) case reflect.Float32: tmp := reflect.ValueOf(pb.Float32(float32(value.Float()))) t.FieldByName("MetricF").Set(tmp) case reflect.Float64: tmp := reflect.ValueOf(pb.Float64(value.Float())) t.FieldByName("MetricD").Set(tmp) default: return nil, fmt.Errorf("Metric of invalid type (type %v)", reflect.TypeOf(f.Interface()).Kind()) } } } } return &e, nil }
// AllocateIDs returns a range of n integer IDs with the given kind and parent // combination. kind cannot be empty; parent may be nil. The IDs in the range // returned will not be used by the datastore's automatic ID sequence generator // and may be used with NewKey without conflict. // // The range is inclusive at the low end and exclusive at the high end. In // other words, valid intIDs x satisfy low <= x && x < high. // // If no error is returned, low + n == high. func AllocateIDs(c appengine.Context, kind string, parent *Key, n int) (low, high int64, err error) { if kind == "" { return 0, 0, errors.New("datastore: AllocateIDs given an empty kind") } if n < 0 { return 0, 0, fmt.Errorf("datastore: AllocateIDs given a negative count: %d", n) } if n == 0 { return 0, 0, nil } req := &pb.AllocateIdsRequest{ ModelKey: keyToProto("", NewIncompleteKey(c, kind, parent)), Size: proto.Int64(int64(n)), } res := &pb.AllocateIdsResponse{} if err := c.Call("datastore_v3", "AllocateIds", req, res, nil); err != nil { return 0, 0, err } // The protobuf is inclusive at both ends. Idiomatic Go (e.g. slices, for loops) // is inclusive at the low end and exclusive at the high end, so we add 1. low = res.GetStart() high = res.GetEnd() + 1 if low+int64(n) != high { return 0, 0, fmt.Errorf("datastore: internal error: could not allocate %d IDs", n) } return low, high, nil }
func lease(c appengine.Context, maxTasks int, queueName string, leaseTime int, groupByTag bool, tag []byte) ([]*Task, error) { req := &taskqueue_proto.TaskQueueQueryAndOwnTasksRequest{ QueueName: []byte(queueName), LeaseSeconds: proto.Float64(float64(leaseTime)), MaxTasks: proto.Int64(int64(maxTasks)), GroupByTag: proto.Bool(groupByTag), Tag: tag, } res := &taskqueue_proto.TaskQueueQueryAndOwnTasksResponse{} callOpts := &appengine_internal.CallOptions{ Timeout: 10 * time.Second, } if err := c.Call("taskqueue", "QueryAndOwnTasks", req, res, callOpts); err != nil { return nil, err } tasks := make([]*Task, len(res.Task)) for i, t := range res.Task { tasks[i] = &Task{ Payload: t.Body, Name: string(t.TaskName), Method: "PULL", ETA: time.Unix(0, *t.EtaUsec*1e3), RetryCount: *t.RetryCount, Tag: string(t.Tag), } } return tasks, nil }
// 客户端申请建立讨论组 func HandleClientBuildGroup(conn *net.TCPConn, recPacket *packet.Packet) { // read readMsg := &pb.PbClientBuildGroup{} packet.Unpack(recPacket, readMsg) uuid := ConnMapUuid.Get(conn).(string) group_name := readMsg.GetGroupName() // 建立讨论组 ret, group_id := groupinfo.BuildGroup(group_name, uuid) tips_msg := "讨论组[" + group_name + "]建立成功" if ret { tips_msg = "讨论组[" + group_name + "]建立失败" } // write writeMsg := &pb.PbServerNotifyBuildGroup{ Build: proto.Bool(ret), GroupId: proto.String(group_id), GroupName: proto.String(group_name), OwnerUuid: proto.String(uuid), TipsMsg: proto.String(tips_msg), Timestamp: proto.Int64(time.Now().Unix()), } SendPbData(conn, packet.PK_ServerNotifyBuildGroup, writeMsg) }
func TestManagerPacketProcessing(t *testing.T) { st := store.New() defer close(st.Ops) in := make(chan Packet) out := make(chan Packet, 100) var m Manager m.run = make(map[int64]*run) m.Alpha = 1 m.Store = st m.In = in m.Out = out m.Ops = st.Ops st.Ops <- store.Op{1, store.MustEncodeSet(node+"/a/addr", "1.2.3.4:5", 0)} st.Ops <- store.Op{2, store.MustEncodeSet("/ctl/cal/0", "a", 0)} m.event(<-mustWait(st, 2)) addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:9999") recvPacket(&m.packet, Packet{ Data: mustMarshal(&msg{Seqn: proto.Int64(2), Cmd: learn, Value: []byte("foo")}), Addr: addr, }) m.pump() assert.Equal(t, 0, m.packet.Len()) }
func (t *Btree) run() { tick := time.Tick(time.Second * 2) for { select { case <-t.exitChan: break case op := <-t.opChan: switch op.GetAction() { case "insert": op.errChan <- t.insert(op.TreeLog) case "delete": op.errChan <- t.dodelete(op.Key) case "update": op.errChan <- t.update(op.TreeLog) case "search": rst, err := t.search(op.Key) op.valueChan <- rst op.errChan <- err } t.Index = proto.Int64(t.GetIndexCursor()) case <-tick: t.gc() } } t.Marshal("treedump.tmp") }
// NewBtreeSize create new btree with custom leafsize/nodesize func NewBtreeSize(leafsize int64, nodesize int64) *Btree { tree := &Btree{ dupnodelist: make(map[int64]int), opChan: make(chan *treeOperation), BtreeMetadata: BtreeMetadata{ Root: proto.Int64(0), Size: proto.Int64(TreeSize), LeafMax: proto.Int64(leafsize), NodeMax: proto.Int64(nodesize), IndexCursor: proto.Int64(0), Nodes: make([][]byte, TreeSize), }, } go tree.run() return tree }
// 客户端申请加入讨论组 func HandleClientJoinGroup(conn *net.TCPConn, recPacket *packet.Packet) { // read readMsg := &pb.PbClientJoinGroup{} packet.Unpack(recPacket, readMsg) from_uuid := readMsg.GetFromUuid() group_id := readMsg.GetGroupId() // note_msg := readMsg.GetNoteMsg() // timestamp := readMsg.GetTimestamp() // 加入讨论组 if ret := groupinfo.JoinGroup(from_uuid, group_id); !ret { return } group_name, _ := groupinfo.GetGroupNameAndOwner(group_id) // write writeMsg := pb.PbServerNotifyJoinGroup{ ApplicantUuid: proto.String(from_uuid), GroupId: proto.String(group_id), GroupName: proto.String(group_name), Timestamp: proto.Int64(time.Now().Unix()), } // 通知所有组员,这个消息不离线存储 group_members := groupinfo.GetAllUuid(group_id) for i := 1; i < len(group_members); i++ { SendPbData(UuidMapConn.Get(group_members[i]).(*net.TCPConn), packet.PK_ServerNotifyJoinGroup, writeMsg) } }
// Given a target channel and a ChannelState protocol message, create a freezer.Channel that // only includes the values changed by the given ChannelState message. When done, write that // frozen.Channel to the datastore. func (server *Server) UpdateFrozenChannel(channel *Channel, state *mumbleproto.ChannelState) { fc := &freezer.Channel{} fc.Id = proto.Uint32(uint32(channel.Id)) if state.Name != nil { fc.Name = state.Name } if state.Parent != nil { fc.ParentId = state.Parent } if len(state.LinksAdd) > 0 || len(state.LinksRemove) > 0 { links := []uint32{} for cid, _ := range channel.Links { links = append(links, uint32(cid)) } fc.Links = links } if state.Position != nil { fc.Position = proto.Int64(int64(*state.Position)) } if len(state.DescriptionHash) > 0 { fc.DescriptionBlob = proto.String(channel.DescriptionBlob) } err := server.freezelog.Put(fc) if err != nil { server.Fatal(err) } server.numLogOps += 1 }
// 客户端请求获取讨论组信息 func HandleClientRequestGroupInfo(conn *net.TCPConn, recPacket *packet.Packet) { readMsg := &pb.PbClientRequestGroupInfo{} packet.Unpack(recPacket, readMsg) uuid := readMsg.GetFromUuid() // timestamp := readMsg.GetTimestamp() groupids := groupinfo.GetAllGroup(uuid) var allGroupInfo []*pb.PbGroupInfo for _, group_id := range groupids { s := groupinfo.GetAllUuid(group_id) group_name, owner_uuid, member_uuid := s[0], s[1], s[2:] gi := &pb.PbGroupInfo{ GroupId: proto.String(group_id), GroupName: proto.String(group_name), OwnerUuid: proto.String(owner_uuid), MemberUuid: member_uuid, } allGroupInfo = append(allGroupInfo, gi) } // write writeMsg := &pb.PbServerResponseGroupInfo{ FromUuid: proto.String(uuid), AllGroupInfo: allGroupInfo, Timestamp: proto.Int64(time.Now().Unix()), } SendPbData(conn, packet.PK_ServerResponseGroupInfo, writeMsg) }
// usageString returns a description of the amount of space taken up by a body // with the given contents and a bool indicating overflow. func (draft *Draft) usageString() (string, bool) { var replyToId *uint64 if draft.inReplyTo != 0 { replyToId = proto.Uint64(1) } var dhPub [32]byte msg := &pond.Message{ Id: proto.Uint64(0), Time: proto.Int64(1 << 62), Body: []byte(draft.body), BodyEncoding: pond.Message_RAW.Enum(), InReplyTo: replyToId, MyNextDh: dhPub[:], Files: draft.attachments, DetachedFiles: draft.detachments, SupportedVersion: proto.Int32(protoVersion), } serialized, err := proto.Marshal(msg) if err != nil { panic("error while serialising candidate Message: " + err.Error()) } s := fmt.Sprintf("%d of %d bytes", len(serialized), pond.MaxSerializedMessage) return s, len(serialized) > pond.MaxSerializedMessage }
// 客户端(群主)申请解散讨论组 func HandleClientDisbandGroup(conn *net.TCPConn, recPacket *packet.Packet) { // read readMsg := &pb.PbClientDisbandGroup{} packet.Unpack(recPacket, readMsg) from_id := readMsg.GetFromUuid() group_id := readMsg.GetGroupId() // timestamp := readMsg.GetTimestamp() // 验证from_id确实是该conn,并且是group_id的群主 group_name, group_owner := groupinfo.GetGroupNameAndOwner(group_id) if from_id != ConnMapUuid.Get(conn).(string) || group_owner != from_id { CloseConn(conn) return } // 解散讨论组 ret := groupinfo.DisbandGroup(from_id, group_id) tips_msg := "解散讨论组[" + group_name + "]成功" if ret { tips_msg = "解散讨论组[" + group_name + "]失败" } // write writeMsg := &pb.PbServerNotifyDisbandGroup{ Disband: proto.Bool(ret), GroupId: proto.String(group_id), GroupName: proto.String(group_name), TipsMsg: proto.String(tips_msg), Timestamp: proto.Int64(time.Now().Unix()), } SendPbData(conn, packet.PK_ServerNotifyDisbandGroup, writeMsg) }
func HandleChatMsg(conn *net.TCPConn, recPacket *packet.Packet) { // read readmsg := &protomsgs.ChatMsg{} proto.Unmarshal(recPacket.Data, readmsg) fmt.Println(readmsg.GetSenderName()) fmt.Println(readmsg.GetMsg()) fmt.Println(utils.TimestampToTimestring(readmsg.GetTimestamp())) // write writemsg := &protomsgs.ChatMsg{ SenderName: proto.String("服务器"), Msg: proto.String("hello,生活真美好."), Timestamp: proto.Int64(time.Now().Unix()), } data, err := proto.Marshal(writemsg) if err != nil { log.Printf("proto.Marshal(writemsg) error: %v", err) return } pac := &packet.Packet{ Len: uint32(len(data) + 6), Type: packet.TYPE_MESSAGE, Data: data, } SendByteStream(conn, pac.GetBytes(), 5*time.Second) }