func server() { ltvsocket.SpawnAcceptor("127.0.0.1:8001", func(self cellnet.CellID, cm interface{}) { switch v := cm.(type) { case ltvsocket.EventAccepted: ltvsocket.SpawnSession(v.Stream(), func(ses cellnet.CellID, sescm interface{}) { switch pkt := sescm.(type) { case *cellnet.Packet: log.Println("server recv:", cellnet.ReflectContent(pkt)) v.Stream().Write(cellnet.BuildPacket(&coredef.TestEchoACK{ Content: proto.String("world"), })) } }) case IError: log.Println(cellnet.ReflectContent(v)) } }) }
func client() { // cellid: 1.1 acceptor // cellid: 1.2 connector // cellid: 1.3 cid := cellnet.Spawn(func(src cellnet.CellID, data interface{}) { switch d := data.(type) { case *cellnet.Packet: log.Println("recv node msg", src.String(), cellnet.ReflectContent(d)) } }) log.Println(cid.String()) nexus.Register(nexus.Dispatcher) // cellid: 1.4 dispatcher.RegisterMessage(nexus.Dispatcher, coredef.TestEchoACK{}, func(src cellnet.CellID, content interface{}) { msg := content.(*coredef.TestEchoACK) log.Println("recv msg callback :", msg.GetContent()) }) }
func client() { ltvsocket.SpawnConnector("127.0.0.1:8001", func(self cellnet.CellID, cm interface{}) { switch v := cm.(type) { case ltvsocket.EventConnected: // new session ltvsocket.SpawnSession(v.Stream(), func(ses cellnet.CellID, sescm interface{}) { switch pkt := sescm.(type) { case *cellnet.Packet: var ack coredef.TestEchoACK if err := proto.Unmarshal(pkt.Data, &ack); err != nil { log.Println(err) } else { log.Println("client recv", ack.String()) done <- true } } }) // send packet on connected v.Stream().Write(cellnet.BuildPacket(&coredef.TestEchoACK{ Content: proto.String("hello"), })) case IError: log.Println(cellnet.ReflectContent(v)) } }) }
// 处理Peer的新会话及会话的消息处理 func PeerHandler(disp *PacketDispatcher) func(cellnet.CellID, interface{}) { return func(peer cellnet.CellID, peerev interface{}) { switch v := peerev.(type) { case ltvsocket.EventNewSession: // 新的连接生成 var msgid uint32 switch peerev.(type) { case ltvsocket.EventConnected: msgid = msgConnected case ltvsocket.EventAccepted: msgid = msgAccepted } ltvsocket.SpawnSession(v.Stream(), func(ses cellnet.CellID, sesev interface{}) { switch data := sesev.(type) { case cellnet.EventInit: // 初始化转通知 disp.Call(ses, &cellnet.Packet{MsgID: msgid}) case ltvsocket.EventClose: // 断开转通知 disp.Call(ses, &cellnet.Packet{MsgID: msgClosed}) case *cellnet.Packet: // 收 disp.Call(ses, data) case proto.Message: // 发 v.Stream().Write(cellnet.BuildPacket(data)) } }) case errInterface: log.Println(cellnet.ReflectContent(v)) } } }