Go-文件系统相关操作

1. TCP 连接

在 Go 中,net 包提供了用于 TCP 连接的工具,可以创建客户端和服务器来实现数据的双向传输。

TCP 客户端示例

下面的代码展示了如何通过 TCP 客户端连接到服务器,并发送和接收数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"fmt"
"net"
)

func main() {
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
fmt.Println("连接服务器失败:", err)
return
}
defer conn.Close()

conn.Write([]byte("Hello, Server!"))
buf := make([]byte, 1024)
n, _ := conn.Read(buf)
fmt.Println("收到服务器响应:", string(buf[:n]))
}

TCP 服务器示例

TCP 服务器用于监听指定端口,接受客户端的连接,并进行数据交互。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
"fmt"
"net"
)

func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("监听端口失败:", err)
return
}
defer listener.Close()

fmt.Println("TCP 服务器已启动,等待连接...")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("接受连接失败:", err)
continue
}
go handleConnection(conn)
}
}

func handleConnection(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 1024)
n, _ := conn.Read(buf)
fmt.Println("收到客户端消息:", string(buf[:n]))
conn.Write([]byte("Hello, Client!"))
}

2. UDP 连接

UDP 是一种无连接协议,适合数据传输不要求可靠性的应用。Go 中的 UDP 客户端和服务器都可以使用 net 包实现。

UDP 客户端示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"fmt"
"net"
)

func main() {
conn, err := net.Dial("udp", "localhost:8081")
if err != nil {
fmt.Println("连接失败:", err)
return
}
defer conn.Close()

conn.Write([]byte("Hello, UDP Server!"))
buf := make([]byte, 1024)
n, _ := conn.Read(buf)
fmt.Println("收到服务器响应:", string(buf[:n]))
}

UDP 服务器示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
"fmt"
"net"
)

func main() {
addr, err := net.ResolveUDPAddr("udp", ":8081")
if err != nil {
fmt.Println("解析地址失败:", err)
return
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println("监听失败:", err)
return
}
defer conn.Close()

fmt.Println("UDP 服务器已启动")
for {
buf := make([]byte, 1024)
n, clientAddr, _ := conn.ReadFromUDP(buf)
fmt.Printf("收到来自 %s 的消息: %s
", clientAddr, string(buf[:n]))
conn.WriteToUDP([]byte("Hello, UDP Client!"), clientAddr)
}
}

3. HTTP 请求处理

HTTP 是 Go 中最常用的协议,标准库 net/http 提供了创建 HTTP 服务器和客户端的简单方法。

HTTP 服务器示例

下面的代码展示了如何使用 Go 创建一个简单的 HTTP 服务器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
"fmt"
"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, HTTP Client!")
}

func main() {
http.HandleFunc("/", handler)
fmt.Println("HTTP 服务器已启动,监听端口 8082")
http.ListenAndServe(":8082", nil)
}

HTTP 客户端示例

使用 http.Get 可以方便地发送 GET 请求,并获取服务器的响应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

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

func main() {
resp, err := http.Get("http://localhost:8082")
if err != nil {
fmt.Println("请求失败:", err)
return
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("收到响应:", string(body))
}