gatewayServer.go 1.3 KB

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