normal.go 1.1 KB

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