package main import ( "encoding/json" "git.noahlan.cn/noahlan/nnet" "git.noahlan.cn/noahlan/nnet/config" "git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/packet" protocol_nnet "git.noahlan.cn/noahlan/nnet/protocol/nnet" rt "git.noahlan.cn/noahlan/nnet/router" "git.noahlan.cn/noahlan/ntool/nlog" "git.noahlan.cn/noahlan/ntool/npool" "math" "time" ) func runServer(addr string) { nginOpts := make([]nnet.RunOption, 0) nginOpts = append(nginOpts, nnet.WithPoolCfg(npool.Config{ PoolSize: math.MaxInt32, ExpiryDuration: time.Second, PreAlloc: false, MaxBlockingTasks: 0, Nonblocking: false, DisablePurge: false, })) nginOpts = append(nginOpts, protocol_nnet.WithNNetProtocol(protocol_nnet.Config{ HeartbeatInterval: 0, HandshakeValidator: nil, })...) ngin := nnet.NewEngine(config.EngineConf{ TaskTimerPrecision: 0, Mode: "dev", Name: "NL", }, nginOpts...) ngin.AddRoutes(rt.Route{ Matches: protocol_nnet.Match{ Route: "ping", Code: 1, }, Handler: func(conn *connection.Connection, pkg packet.IPacket) { nlog.Info("client ping, server pong -> ") err := conn.Send(protocol_nnet.Header{ PacketType: protocol_nnet.Data, MessageHeader: protocol_nnet.MessageHeader{ MsgType: protocol_nnet.Request, ID: 1, Route: "pong", }, }, []byte("1")) nlog.Must(err) }, }) defer ngin.Stop() err := ngin.ListenTCP(config.TCPServerConf{ Protocol: "tcp", Addr: addr, }) if err != nil { return } } func runClient(addr string) (*nnet.Engine, *connection.Connection) { chReady := make(chan struct{}) nginOpts := make([]nnet.RunOption, 0) nginOpts = append(nginOpts, nnet.WithPoolCfg(npool.Config{ PoolSize: math.MaxInt32, ExpiryDuration: time.Second, PreAlloc: false, MaxBlockingTasks: 0, Nonblocking: false, DisablePurge: false, })) nginOpts = append(nginOpts, protocol_nnet.WithNNetClientProtocol(func() { chReady <- struct{}{} })...) ngin := nnet.NewEngine(config.EngineConf{ TaskTimerPrecision: 0, Mode: "dev", Name: "NL", }, nginOpts...) ngin.AddRoutes(rt.Route{ Matches: protocol_nnet.Match{ Route: "test.client", Code: 1, }, Handler: func(conn *connection.Connection, pkg packet.IPacket) { nlog.Info("client hahaha") }, }) conn, err := ngin.Dial(addr) nlog.Must(err) handshake, err := json.Marshal(&protocol_nnet.HandshakeReq{ Version: "1.0.0", Type: "test", ClientId: "a", ClientSecret: "a", Payload: map[string]string{ "pl": "test-data", }, }) nlog.Must(err) packer := protocol_nnet.NewPacker(protocol_nnet.NewRouteMap()) hsd, err := packer.Pack(protocol_nnet.Header{ PacketType: protocol_nnet.Handshake, MessageHeader: protocol_nnet.MessageHeader{ MsgType: 0, ID: 0, Route: "", }, }, handshake) nlog.Must(err) err = conn.SendBytes(hsd) nlog.Must(err) <-chReady return ngin, conn }