1. import net

Go TCP编程 - 图1

TCP服务端

  1. listen, err := net.Listen("tcp", "127.0.0.1:9001")
  2. if err != nil {
  3. log.Fatalf("Listen failed %s", err.Error())
  4. return
  5. }
  1. for {
  2. conn, err := listen.Accept()
  3. if err != nil {
  4. log.Fatalf("Accept Failed %s", err.Error())
  5. }
  6. go process(conn)
  7. }
  1. func process(conn net.Conn) {
  2. defer func(conn net.Conn) {
  3. _ = conn.Close()
  4. }(conn) // 关闭连接
  5. for {
  6. var buf [128]byte // 创建缓冲区
  7. reader := bufio.NewReader(conn)
  8. n, err := reader.Read(buf[:])
  9. // 判断客户端连接是否关闭
  10. if err == io.EOF {
  11. fmt.Println("客户端连接已关闭")
  12. break
  13. }
  14. if err != nil {
  15. log.Printf("read from client faild , %s\n", err.Error())
  16. break
  17. }
  18. recvStr := string(buf[:n])
  19. fmt.Printf("接受到客户端发送的数据: %s", recvStr)
  20. _, _ = conn.Write([]byte(recvStr))
  21. }
  22. }

TCP客户端

  1. conn,err := net.Dial("tcp","127.0.0.1:9001")
  2. if err != nil {
  3. fmt.Printf("connection diald error : %s\n",err.Error())
  4. return
  5. }
  6. defer conn.Close()
  1. num,err := conn.Write([]byte("hello"))
  2. if err != nil {
  3. fmt.Printf("write error : %s\n",err.Error())
  4. return
  5. }
  6. fmt.Printf("write num : %d\n",num)
  1. buf := make([]byte, 1024)
  2. for {
  3. if _, err := conn.Read(buf); err != nil {
  4. if err == io.EOF {
  5. fmt.Println("服务器连接断开")
  6. return
  7. } else {
  8. fmt.Printf("error : %s \n", err.Error())
  9. return
  10. }
  11. }
  12. fmt.Printf("server reply : %s\n", string(buf))
  13. }