funcmain() { // Listen on TCP port 8080 on all available unicast and // any unicast IP addresses. listen, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println(err) return } defer listen.Close()
// Infinite loop to handle incoming connections for { conn, err := listen.Accept() if err != nil { fmt.Println(err) continue } // Launch a new goroutine to handle the connection go handleConnection(conn) } }
funchandleConnection(conn net.Conn) { defer conn.Close() buffer := make([]byte, 1024) // Read the incoming connection into the buffer. _, err := conn.Read(buffer) if err != nil { fmt.Println(err) return } // Send a response back to the client. conn.Write([]byte("Received: " + string(buffer))) }
客户端
package main
import ( "net" "fmt" )
funcmain() { // Connect to the server at localhost on port 8080. conn, err := net.Dial("tcp", "localhost:8080") if err != nil { fmt.Println(err) return } defer conn.Close()
// Send a message to the server. conn.Write([]byte("Hello, server!")) buffer := make([]byte, 1024) // Read the response from the server. conn.Read(buffer) fmt.Println(string(buffer)) }
funcmain() { // Listen for incoming UDP packets on port 8080. conn, err := net.ListenPacket("udp", ":8080") if err != nil { fmt.Println(err) return } defer conn.Close()
buffer := make([]byte, 1024) // Read the incoming packet data into the buffer. n, addr, err := conn.ReadFrom(buffer) if err != nil { fmt.Println(err) return } fmt.Println("Received: ", string(buffer[:n])) // Write a response to the client's address. conn.WriteTo([]byte("Message received!"), addr) }
客户端
package main
import ( "net" "fmt" )
funcmain() { // Resolve the server's address. addr, err := net.ResolveUDPAddr("udp", "localhost:8080") if err != nil { fmt.Println(err) return }
// Dial a connection to the resolved address. conn, err := net.DialUDP("udp", nil, addr) if err != nil { fmt.Println(err) return } defer conn.Close()
// Write a message to the server. conn.Write([]byte("Hello, server!")) buffer := make([]byte, 1024) // Read the response from the server. conn.Read(buffer) fmt.Println(string(buffer)) }
服务器从任何客户端读取消息并发送响应。客户端发送消息并等待响应。
示例 3:并发 TCP 服务器
并发允许同时处理多个客户端。
package main
import ( "net" "fmt" )
funcmain() { // Listen on TCP port 8080. listener, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println(err) return } defer listener.Close()
for { // Accept a connection. conn, err := listener.Accept() if err != nil { fmt.Println(err) continue } // Handle the connection in a new goroutine. go handleConnection(conn) } }
funchandleConnection(conn net.Conn) { defer conn.Close() buffer := make([]byte, 1024) // Read the incoming connection. conn.Read(buffer) fmt.Println("Received:", string(buffer)) // Respond to the client. conn.Write([]byte("Message received!")) }
funcmain() { // Create a new router. r := mux.NewRouter() // Register a handler function for the root path. r.HandleFunc("/", homeHandler) http.ListenAndServe(":8080", r) }
funchomeHandler(w http.ResponseWriter, r *http.Request) { // Respond with a welcome message. fmt.Fprint(w, "Welcome to Home!") }
这段代码设置了一个 HTTP 服务器,并为根路径定义了一个处理函数。
示例 5:HTTPS 服务器
实现 HTTPS 服务器可以确保安全通信。
package main
import ( "net/http" "log" )
funcmain() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Respond with a message. w.Write([]byte("Hello, this is an HTTPS server!")) }) // Use the cert.pem and key.pem files to secure the server. log.Fatal(http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil)) }
服务器使用 TLS(传输层安全性)来加密通信。
示例 6:自定义 TCP 协议
可以使用自定义的 TCP 协议进行专门的通信。
package main
import ( "net" "strings" )
funcmain() { // Listen on TCP port 8080. listener, err := net.Listen("tcp", ":8080") if err != nil { panic(err) } defer listener.Close()
for { // Accept a connection. conn, err := listener.Accept() if err != nil { panic(err) } // Handle the connection in a new goroutine. go handleConnection(conn) } }
funchandleConnection(conn net.Conn) { defer conn.Close() buffer := make([]byte, 1024) // Read the incoming connection. conn.Read(buffer) // Process custom protocol command. cmd := strings.TrimSpace(string(buffer)) if cmd == "TIME" { conn.Write([]byte("The current time is: " + time.Now().String())) } else { conn.Write([]byte("Unknown command")) } }
// Define a rate limiter allowing two requests per second with a burst capacity of five. var limiter = rate.NewLimiter(2, 5)
funchandler(w http.ResponseWriter, r *http.Request) { // Check if request is allowed by the rate limiter. if !limiter.Allow() { http.Error(w, "Too Many Requests", http.StatusTooManyRequests) return } w.Write([]byte("Welcome!")) }