1. 程式人生 > >22-golang簡單收發伺服器程式碼

22-golang簡單收發伺服器程式碼

先寫客戶端

客戶端傳送資訊

func main() {

   fmt.Println("請輸入:")
   var message string
   fmt.Scan(&message)

   conn, err := net.Dial("tcp", "127.0.0.1:8000")
   if err != nil {
      fmt.Println("err = ", err)
      return
   }

   defer conn.Close()

   conn.Write([]byte(message))

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

   fmt.Println("伺服器回覆:", string(bytes[:num]))

}

然後是伺服器

func main() {

   listener, err := net.Listen("tcp", "127.0.0.1:8000")
   if err != nil {
      fmt.Println("err = ", err)
      return
   }

   defer listener.Close()

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

      handleConn(conn)
   }

}

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

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

   conn.Write(bytes[:num])

}