Go语言在Linux网络编程方面表现出色,它提供了丰富的库和API来处理网络相关的任务。以下是一些常见的Go语言网络编程场景和示例代码:
package main
import (
"bufio"
"fmt"
"net"
)
func main() {
// 监听端口
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer listener.Close()
fmt.Println("Server is listening on port 8080...")
for {
// 接受客户端连接
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting:", err)
continue
}
// 处理客户端连接
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading:", err)
break
}
fmt.Printf("Received: %s", message)
}
}
package main
import (
"fmt"
"net"
)
func main() {
// 连接到服务器
conn, err := net.Dial("tcp", "127.0.0.1:8080")
if err != nil {
fmt.Println("Error connecting:", err)
return
}
defer conn.Close()
_, err = conn.Write([]byte("Hello, Server!\n"))
if err != nil {
fmt.Println("Error writing:", err)
return
}
reader := bufio.NewReader(conn)
message, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading:", err)
return
}
fmt.Printf("Server response: %s", message)
}
package main
import (
"fmt"
"net"
)
func main() {
// 创建UDP连接
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: 8080,
})
if err != nil {
fmt.Println("Error creating UDP connection:", err)
return
}
defer conn.Close()
_, err = conn.Write([]byte("Hello, UDP Server!"))
if err != nil {
fmt.Println("Error writing:", err)
return
}
buffer := make([]byte, 1024)
n, _, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println("Error reading:", err)
return
}
fmt.Printf("Server response: %s", string(buffer[:n]))
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://api.example.com/data")
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
fmt.Printf("Response: %s", string(body))
}
这些示例展示了如何使用Go语言在Linux上进行基本的网络编程,包括TCP和UDP通信以及HTTP请求。你可以根据自己的需求进行扩展和修改。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: go语言的高级并发模式怎么应用