github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/poller/cmd/server/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/weedge/lib/log"
     8  	"github.com/weedge/lib/poller"
     9  	"github.com/weedge/lib/poller/cmd/common"
    10  )
    11  
    12  type MockServerHandler struct {
    13  }
    14  
    15  func (m *MockServerHandler) OnConnect(c *poller.Conn) {
    16  	log.Info("connect:", c.GetFd(), c.GetAddr())
    17  }
    18  
    19  func (m *MockServerHandler) OnMessage(c *poller.Conn, bytes []byte) {
    20  	log.Info("read:", string(bytes), "from fd:", c.GetFd())
    21  	encoder := poller.NewHeaderLenEncoder(common.HeaderLen, common.MaxLen)
    22  	res := fmt.Sprintf("got it: %s", bytes)
    23  	err := encoder.EncodeToWriter(c, []byte(res))
    24  	if err != nil {
    25  		log.Error("res", res, "EncodeToFD err:", err.Error())
    26  	}
    27  	log.Info("res", res, "EncodeToFD", c.GetFd(), "ok")
    28  }
    29  
    30  func (m *MockServerHandler) OnClose(c *poller.Conn, err error) {
    31  	log.Info("close:", c.GetFd(), err)
    32  }
    33  
    34  func main() {
    35  	server, err := poller.NewServer(":8085", &MockServerHandler{}, poller.WithDecoder(poller.NewHeaderLenDecoder(common.HeaderLen)),
    36  		poller.WithTimeout(10*time.Second, 3600*time.Second), poller.WithReadBufferLen(10))
    37  	if err != nil {
    38  		log.Info("err")
    39  		return
    40  	}
    41  
    42  	server.Run()
    43  }