在Linux上使用Golang进行网络编程,主要涉及到以下几个方面:
import (
"fmt"
"io"
"net"
"os"
)
Dial函数创建TCP连接,或者使用ResolveUDPAddr和DialUDP函数创建UDP连接。// TCP连接
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
fmt.Println("Error connecting:", err)
os.Exit(1)
}
defer conn.Close()
// UDP连接
udpAddr, err := net.ResolveUDPAddr("udp", "example.com:80")
if err != nil {
fmt.Println("Error resolving UDP address:", err)
os.Exit(1)
}
conn, err := net.DialUDP("udp", nil, udpAddr)
if err != nil {
fmt.Println("Error connecting:", err)
os.Exit(1)
}
defer conn.Close()
conn.Write和conn.Read方法发送和接收数据。对于UDP连接,使用conn.WriteToUDP和conn.ReadFromUDP方法。// 发送数据
_, err = conn.Write([]byte("Hello, World!"))
if err != nil {
fmt.Println("Error sending data:", err)
os.Exit(1)
}
// 接收数据
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error receiving data:", err)
os.Exit(1)
}
fmt.Println("Received:", string(buffer[:n]))
net.Listen函数监听端口,然后使用goroutine处理每个连接。listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error listening:", err)
os.Exit(1)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
go handleConnection(conn)
}
以上就是在Linux上使用Golang进行网络编程的基本步骤。根据实际需求,可以进一步优化和完善代码。