1. 程式人生 > >20-golang簡單併發伺服器

20-golang簡單併發伺服器

func main() {
   listener, err := net.Listen("tcp", "127.0.0.1:8080")

   if err != nil {
      fmt.Println("err是", err)
      return
   }

   defer listener.Close()

   for {
      conn, err := listener.Accept()
      if err != nil {
         fmt.Println("err是", err)
         return
      }

      go handleConnection(conn)
   }

}

func handleConnection(conn net.Conn) {
   defer conn.Close()

   addr := conn.RemoteAddr().String()
   fmt.Println(addr, "連線成功")

   bytes := make([]byte, 2048)
   num, err := conn.Read(bytes)
   if err != nil {
      fmt.Println("err是", err)
      return
   }

   conn.Write(bytes[:num])

}

如果簡化一下,就是

func main() {
   listener, _ := net.Listen("tcp", "127.0.0.1:8080")

   defer listener.Close()

   for {
      conn, _ := listener.Accept()

      go handleConnection(conn)
   }

}

func handleConnection(conn net.Conn) {
   defer conn.Close()

   addr := conn.RemoteAddr().String()
   fmt.Println(addr, "連線成功")

   bytes := make([]byte, 2048)
   num, _ := conn.Read(bytes)

   conn.Write(bytes[:num])

}

然後我們再增加一個退出

func main() {

   listener, _ := net.Listen("tcp", "127.0.0.1:8080")

   defer listener.Close()

   for {

      conn, _ := listener.Accept()

      go handleConn(conn)
   }

}
func handleConn(conn net.Conn) {
   defer conn.Close()

   addr := conn.RemoteAddr()
   fmt.Println(addr, "連線成功")

   bytes := make([]byte, 2048)
   for {
      num, _ := conn.Read(bytes)

      if string(bytes[:num]) == "exit" {
         fmt.Println("退出")
         return     
      }

      conn.Write(bytes[:num])
   }

}