您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

tcp_server.go 1.5 KiB

3 周前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package connect
  2. import (
  3. "context"
  4. "egg-im/pkg/logger"
  5. "egg-im/pkg/pb"
  6. "egg-im/pkg/rpc"
  7. "time"
  8. "go.uber.org/zap"
  9. "github.com/alberliu/gn"
  10. )
  11. var encoder = gn.NewHeaderLenEncoder(2, 1024)
  12. var server *gn.Server
  13. // StartTCPServer 启动TCP服务器
  14. func StartTCPServer(addr string) {
  15. gn.SetLogger(logger.Sugar)
  16. var err error
  17. server, err = gn.NewServer(addr, &handler{},
  18. gn.WithDecoder(gn.NewHeaderLenDecoder(2)),
  19. gn.WithEncoder(gn.NewHeaderLenEncoder(2, 1024)),
  20. gn.WithReadBufferLen(256),
  21. gn.WithTimeout(11*time.Minute),
  22. gn.WithAcceptGNum(10),
  23. gn.WithIOGNum(100))
  24. if err != nil {
  25. logger.Sugar.Error(err)
  26. panic(err)
  27. }
  28. server.Run()
  29. }
  30. type handler struct{}
  31. func (*handler) OnConnect(c *gn.Conn) {
  32. // 初始化连接数据
  33. conn := &Conn{
  34. CoonType: CoonTypeTCP,
  35. TCP: c,
  36. }
  37. c.SetData(conn)
  38. logger.Logger.Debug("connect:", zap.Int32("fd", c.GetFd()), zap.String("addr", c.GetAddr()))
  39. }
  40. func (*handler) OnMessage(c *gn.Conn, bytes []byte) {
  41. conn := c.GetData().(*Conn)
  42. conn.HandleMessage(bytes)
  43. }
  44. func (*handler) OnClose(c *gn.Conn, err error) {
  45. conn, ok := c.GetData().(*Conn)
  46. if !ok || conn == nil {
  47. return
  48. }
  49. logger.Logger.Debug("close", zap.String("addr", c.GetAddr()), zap.Int64("user_id", conn.UserId),
  50. zap.Int64("device_id", conn.DeviceId), zap.Error(err))
  51. DeleteConn(conn.DeviceId)
  52. if conn.UserId != 0 {
  53. _, _ = rpc.GetLogicIntClient().Offline(context.TODO(), &pb.OfflineReq{
  54. UserId: conn.UserId,
  55. DeviceId: conn.DeviceId,
  56. ClientAddr: c.GetAddr(),
  57. })
  58. }
  59. }