gatewayServer.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package gatewayServer
  2. import (
  3. "fmt"
  4. "io"
  5. "lc-fangdaosha/global"
  6. "log"
  7. "net"
  8. "sync/atomic"
  9. )
  10. var ipAddress = global.Config.Foreign.GatewayServer
  11. var ConnMap = make(map[string]net.Conn, 50)
  12. var openDebug bool = false
  13. // GatewayServe 网关服务
  14. func GatewayServe() {
  15. listen, err := net.Listen("tcp", ipAddress)
  16. if err != nil {
  17. log.Fatalln("服务启动失败 ", err)
  18. }
  19. for {
  20. accept, err := listen.Accept()
  21. if err != nil {
  22. log.Fatalln("获取连接失败 ", err)
  23. }
  24. go handleConn(accept)
  25. }
  26. }
  27. var n int32
  28. // handleConn 处理连接
  29. func handleConn(c net.Conn) {
  30. defer func() {
  31. atomic.AddInt32(&n, -1)
  32. }()
  33. atomic.AddInt32(&n, 1)
  34. fmt.Printf("连接数 %d\n", atomic.LoadInt32(&n))
  35. fmt.Printf("当前连接 %s\n", c.RemoteAddr())
  36. //var filterChan = make(chan []byte, 32)
  37. var dataChan = make(chan []byte, 32)
  38. readData := func() {
  39. for {
  40. var buf = make([]byte, 1024)
  41. n, err := c.Read(buf)
  42. if err != nil {
  43. if err == io.EOF {
  44. log.Println("已到达文件结束")
  45. break
  46. }
  47. log.Println("读数据失败", err)
  48. break
  49. }
  50. if n == 0 {
  51. log.Println("未读取到数据")
  52. break
  53. }
  54. dataChan <- buf[:n]
  55. }
  56. }
  57. handleData := func() {
  58. for {
  59. v, ok := <-dataChan
  60. if !ok {
  61. return
  62. }
  63. adu := UnPack(v)
  64. c.RemoteAddr()
  65. ParseAndResponse(adu, c)
  66. }
  67. }
  68. go readData()
  69. go handleData()
  70. }