golang-im聊天
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

74 wiersze
1.5 KiB

  1. package connect
  2. import (
  3. "context"
  4. "gim/pkg/logger"
  5. "gim/pkg/pb"
  6. "gim/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. }