Go语言网络编程

编程 · 02-20 · 115 人浏览

网络编程三要素:

  • IP地址:通过IP地址找到指定计算机
  • 端口:通过端口找到指定进程
  • 协议:定义通信规则,符合协议则可以通信,不符合不能通信

TCP/IP协议:

  • 建立连接:三次握手
  • 释放连接:四次挥手

TCP编程

client\main.go

package main

import (
  "bufio"
  "fmt"
  "net"
  "os"
)

func main() {
  println("客户端启动...")
  conn, err := net.Dial("tcp", "127.0.0.1:8080") // 可简写为:8080,冒号前面默认是本机地址
  if err != nil {
    println("客户端连接失败:", err.Error())
    return
  }
  defer conn.Close()
  println("连接成功,conn:", conn.LocalAddr().String())

  // 客户端发送数据
  print("发送数据:")
  reader := bufio.NewReader(os.Stdin) //从标准输入读取数据
  str, err := reader.ReadString('\n')
  if err != nil {
    println("终端输入数据失败:", err.Error())
    return
  }
  // 将str发送给服务端
  n, err := conn.Write([]byte(str))
  if err != nil {
    println("客户端发送数据失败:", err.Error())
  }

  fmt.Printf("客户端发送数据成功,一共发送了 %d 字节数据,并退出", n)
}

server\main.go

package main

import "net"

func process(conn net.Conn) {
  defer conn.Close()
  buf := make([]byte, 1024)
  n, err := conn.Read(buf) // 读取客户端数据,放入切片
  if err != nil {
    println("读取数据失败:", err.Error())
    return
  }
  println("接收到数据:", string(buf[:n]))
}

func main() {
  println("服务端启动...")
  listen, err := net.Listen("tcp", "127.0.0.1:8080")
  if err != nil {
    println("服务端监听失败:", err.Error())
    return
  }
  defer listen.Close()
  println("监听成功,listen:", listen.Addr().String())

  // 等待客户端连接
  for {
    conn, err := listen.Accept()
    if err != nil {
      println("客户端连接失败:", err.Error())
    } else {
      println("客户端连接成功:", conn.RemoteAddr().String())
      go process(conn) // 启动一个协程处理客户端请求
    }
  }
}

UDP编程

server

package main

import (
  "fmt"
  "net"
)

func main() {
  listen, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 30000})
  if err != nil {
    fmt.Println("Listen error:", err)
    return
  }
  defer listen.Close()

  for {
    var data [1024]byte
    n, addr, err := listen.ReadFromUDP(data[:]) // 接收数据
    if err != nil {
      fmt.Println("ReadFromUDP error:", err)
      continue
    }
    fmt.Println("Received from", addr, "data:", string(data[:n]))

    _, err = listen.WriteToUDP([]byte("Hello, client!"), addr) // 发送数据
    if err != nil {
      fmt.Println("WriteToUDP error:", err)
      continue
    }
  }
}

client

package main

import (
  "fmt"
  "net"
)

func main() {
  socket, err := net.DialUDP("udp", nil, &net.UDPAddr{
    IP:   net.IPv4(0, 0, 0, 0),
    Port: 30000,
  })
  if err != nil {
    fmt.Println("Error connecting to server:", err)
    return
  }
  defer socket.Close()

  sendData := []byte("Hello, world!")
  _, err = socket.Write(sendData)
  if err != nil {
    fmt.Println("Error sending data to server:", err)
    return
  }

  data := make([]byte, 1024)
  n, _, err := socket.ReadFromUDP(data)
  if err != nil {
    fmt.Println("Error reading data from server:", err)
    return
  }
  fmt.Println("Received data from server:", string(data[:n]))
}

http编程

client

package main

import (
  "fmt"
  "io"
  "net/http"
)

func main() {
  clint := http.Client{}
  resp, err := clint.Get("http://www.baidu.com")
  if err != nil {
    println("clint.Get error:", err)
    return
  }
  defer resp.Body.Close()

  fmt.Println(resp.Status)                     // 200 OK
  fmt.Println(resp.StatusCode)                 // 200
  fmt.Println(resp.Header.Get("Content-Type")) // application/x-gzip

  println(resp.Request.URL.String()) // http://www.baidu.com

  body, err := io.ReadAll(resp.Body)
  if err != nil {
    panic(err)
  }
  fmt.Println(string(body))
}

server

func main() {
  // 注册路由
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "主页")
  })
  http.HandleFunc("/name", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "name")
  })

  fmt.Println("http server start...")
  if err := http.ListenAndServe(":8080", nil); err != nil {
    fmt.Println("http start failed, err:", err)
    return
  }
}
Go
Theme Jasmine by Kent Liao