Go语言Socket短连接

Socket.go代码
var (  
   wafObjectModel = new(models.WafLogModel)
)

type WafSocketListenService struct {  
}

func (this *WafSocketListenService) Run() {  
   tcpAddr, err := net.ResolveTCPAddr("tcp4", ":443")
   if err != nil {
      log.Println("ResolveTCPAddr error : ", err)
      os.Exit(1)
   }
   listener, err := net.ListenTCP("tcp", tcpAddr)
   if err != nil {
      log.Println("listen tcp error : ", err)
      os.Exit(1)
   }
   for {
      conn, err := listener.Accept()
      if err != nil {
         continue
      }
      go this.HandleClient(conn) //创建一个goroutinue处理
   }
}

func (this *WafSocketListenService) HandleClient(conn net.Conn) {  
   defer conn.Close()
   //读取时间1秒,超过1秒直接关闭
   conn.SetReadDeadline(time.Now().Add(time.Second * 1))
   result, _ := ioutil.ReadAll(conn)
   var resultMap = map[string]interface{}{}
   err := json.Unmarshal(result, &resultMap)
   if err != nil {
      log.Println("no json")
   } else {
      wafObjectModel.Insert(resultMap)
   }
}

郝先生

继续阅读此作者的更多文章