link.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 Secret struct {
  10. Password string
  11. Conn *Conn
  12. }
  13. func NewSecret(p string, conn *Conn) *Secret {
  14. return &Secret{
  15. Password: p,
  16. Conn: conn,
  17. }
  18. }
  19. type Link struct {
  20. Id int //id
  21. ConnType string //连接类型
  22. Host string //目标
  23. En int //加密
  24. De int //解密
  25. Crypt bool //加密
  26. Conn *Conn
  27. Flow *file.Flow
  28. UdpListener *net.UDPConn
  29. Rate *rate.Rate
  30. UdpRemoteAddr *net.UDPAddr
  31. MsgCh chan []byte
  32. MsgConn *Conn
  33. StatusCh chan bool
  34. FinishUse bool
  35. }
  36. 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 {
  37. return &Link{
  38. Id: id,
  39. ConnType: connType,
  40. Host: host,
  41. En: en,
  42. De: de,
  43. Crypt: crypt,
  44. Conn: c,
  45. Flow: flow,
  46. UdpListener: udpListener,
  47. Rate: rate,
  48. UdpRemoteAddr: UdpRemoteAddr,
  49. MsgCh: make(chan []byte),
  50. StatusCh: make(chan bool),
  51. }
  52. }
  53. func (s *Link) Run(flow bool) {
  54. go func() {
  55. for {
  56. select {
  57. case content := <-s.MsgCh:
  58. if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
  59. s.FinishUse = true
  60. if s.Conn != nil {
  61. s.Conn.Close()
  62. }
  63. return
  64. } else {
  65. if s.Conn == nil {
  66. return
  67. }
  68. if s.UdpListener != nil && s.UdpRemoteAddr != nil {
  69. s.UdpListener.WriteToUDP(content, s.UdpRemoteAddr)
  70. } else {
  71. s.Conn.Write(content)
  72. }
  73. if flow {
  74. s.Flow.Add(0, len(content))
  75. }
  76. if s.ConnType == common.CONN_UDP {
  77. return
  78. }
  79. s.MsgConn.WriteWriteSuccess(s.Id)
  80. }
  81. pool.PutBufPoolCopy(content)
  82. }
  83. }
  84. }()
  85. }