golang-im聊天
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

71 satır
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 := c.GetData().(*Conn)
  46. logger.Logger.Debug("close", zap.String("addr", c.GetAddr()), zap.Int64("user_id", conn.UserId),
  47. zap.Int64("device_id", conn.DeviceId), zap.Error(err))
  48. DeleteConn(conn.DeviceId)
  49. if conn.UserId != 0 {
  50. _, _ = rpc.GetLogicIntClient().Offline(context.TODO(), &pb.OfflineReq{
  51. UserId: conn.UserId,
  52. DeviceId: conn.DeviceId,
  53. ClientAddr: c.GetAddr(),
  54. })
  55. }
  56. }