link.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package conn
  2. import (
  3. "github.com/cnlh/nps/lib/common"
  4. "github.com/cnlh/nps/lib/file"
  5. "github.com/cnlh/nps/lib/pool"
  6. "github.com/cnlh/nps/lib/rate"
  7. "net"
  8. )
  9. type Link struct {
  10. Id int //id
  11. ConnType string //连接类型
  12. Host string //目标
  13. En int //加密
  14. De int //解密
  15. Crypt bool //加密
  16. Conn *Conn
  17. Flow *file.Flow
  18. UdpListener *net.UDPConn
  19. Rate *rate.Rate
  20. UdpRemoteAddr *net.UDPAddr
  21. MsgCh chan []byte
  22. MsgConn *Conn
  23. StatusCh chan bool
  24. }
  25. func NewLink(id int, connType string, host string, en, de int, crypt bool, c *Conn, flow *file.Flow, udpListener *net.UDPConn, rate *rate.Rate, UdpRemoteAddr *net.UDPAddr) *Link {
  26. return &Link{
  27. Id: id,
  28. ConnType: connType,
  29. Host: host,
  30. En: en,
  31. De: de,
  32. Crypt: crypt,
  33. Conn: c,
  34. Flow: flow,
  35. UdpListener: udpListener,
  36. Rate: rate,
  37. UdpRemoteAddr: UdpRemoteAddr,
  38. MsgCh: make(chan []byte),
  39. StatusCh: make(chan bool),
  40. }
  41. }
  42. func (s *Link) Run(flow bool) {
  43. go func() {
  44. for {
  45. select {
  46. case content := <-s.MsgCh:
  47. if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
  48. if s.Conn != nil {
  49. s.Conn.Close()
  50. }
  51. return
  52. } else {
  53. if s.UdpListener != nil && s.UdpRemoteAddr != nil {
  54. s.UdpListener.WriteToUDP(content, s.UdpRemoteAddr)
  55. } else {
  56. s.Conn.Write(content)
  57. }
  58. if flow {
  59. s.Flow.Add(0, len(content))
  60. }
  61. if s.ConnType == common.CONN_UDP {
  62. return
  63. }
  64. s.MsgConn.WriteWriteSuccess(s.Id)
  65. pool.PutBufPoolCopy(content)
  66. }
  67. }
  68. }
  69. }()
  70. }