normal.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package conn
  2. import (
  3. "github.com/cnlh/nps/lib/crypt"
  4. "github.com/cnlh/nps/lib/pool"
  5. "github.com/cnlh/nps/lib/rate"
  6. "io"
  7. )
  8. type CryptConn struct {
  9. conn io.ReadWriteCloser
  10. crypt bool
  11. rate *rate.Rate
  12. }
  13. func NewCryptConn(conn io.ReadWriteCloser, crypt bool, rate *rate.Rate) *CryptConn {
  14. c := new(CryptConn)
  15. c.conn = conn
  16. c.crypt = crypt
  17. c.rate = rate
  18. return c
  19. }
  20. //加密写
  21. func (s *CryptConn) Write(b []byte) (n int, err error) {
  22. n = len(b)
  23. if s.crypt {
  24. if b, err = crypt.AesEncrypt(b, []byte(cryptKey)); err != nil {
  25. return
  26. }
  27. }
  28. if b, err = GetLenBytes(b); err != nil {
  29. return
  30. }
  31. _, err = s.conn.Write(b)
  32. if s.rate != nil {
  33. s.rate.Get(int64(n))
  34. }
  35. return
  36. }
  37. //解密读
  38. func (s *CryptConn) Read(b []byte) (n int, err error) {
  39. var lens int
  40. var buf []byte
  41. var rb []byte
  42. if lens, err = GetLen(s.conn); err != nil || lens > len(b) || lens < 0 {
  43. return
  44. }
  45. buf = pool.BufPool.Get().([]byte)
  46. defer pool.BufPool.Put(buf)
  47. if n, err = io.ReadFull(s.conn, buf[:lens]); err != nil {
  48. return
  49. }
  50. if s.crypt {
  51. if rb, err = crypt.AesDecrypt(buf[:lens], []byte(cryptKey)); err != nil {
  52. return
  53. }
  54. } else {
  55. rb = buf[:lens]
  56. }
  57. copy(b, rb)
  58. n = len(rb)
  59. if s.rate != nil {
  60. s.rate.Get(int64(n))
  61. }
  62. return
  63. }
  64. func (s *CryptConn) Close() error {
  65. return s.conn.Close()
  66. }