日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當(dāng)前位置:首頁 > 科技  > 軟件

Go 語言高級網(wǎng)絡(luò)編程

來源: 責(zé)編: 時(shí)間:2023-11-06 17:18:54 240觀看
導(dǎo)讀一、簡介Go(Golang)中的網(wǎng)絡(luò)編程具有易用性、強(qiáng)大性和樂趣。本指南深入探討了網(wǎng)絡(luò)編程的復(fù)雜性,涵蓋了協(xié)議、TCP/UDP 套接字、并發(fā)等方面的內(nèi)容,并附有詳細(xì)的注釋。二、關(guān)鍵概念1. 網(wǎng)絡(luò)協(xié)議TCP(傳輸控制協(xié)議):確保可靠的數(shù)據(jù)

一、簡介

Go(Golang)中的網(wǎng)絡(luò)編程具有易用性、強(qiáng)大性和樂趣。本指南深入探討了網(wǎng)絡(luò)編程的復(fù)雜性,涵蓋了協(xié)議、TCP/UDP 套接字、并發(fā)等方面的內(nèi)容,并附有詳細(xì)的注釋。hyF28資訊網(wǎng)——每日最新資訊28at.com

hyF28資訊網(wǎng)——每日最新資訊28at.com

二、關(guān)鍵概念

1. 網(wǎng)絡(luò)協(xié)議

  • TCP(傳輸控制協(xié)議):確保可靠的數(shù)據(jù)傳輸。
  • UDP(用戶數(shù)據(jù)報(bào)協(xié)議):更快,但不保證數(shù)據(jù)傳遞。

2. 套接字

  • TCP 套接字:用于面向連接的通信。
  • UDP 套接字:用于無連接通信。

3. 并發(fā)

  • Goroutines(協(xié)程):允許在代碼中實(shí)現(xiàn)并行處理。
  • Channels(通道):用于協(xié)程之間的通信。

三、示例

示例 1:TCP 服務(wù)器和客戶端

TCP 服務(wù)器和客戶端示例演示了TCP通信的基礎(chǔ)。hyF28資訊網(wǎng)——每日最新資訊28at.com

服務(wù)器:hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "net" "fmt")func main() { // 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) }}func handleConnection(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)))}

客戶端:hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "net" "fmt")func main() { // 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))}

服務(wù)器在端口8080上等待連接,讀取傳入的消息并發(fā)送響應(yīng)。客戶端連接到服務(wù)器,發(fā)送消息并打印服務(wù)器的響應(yīng)。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 2:UDP 服務(wù)器和客戶端

與TCP不同,UDP是無連接的。以下是UDP服務(wù)器和客戶端的實(shí)現(xiàn)。hyF28資訊網(wǎng)——每日最新資訊28at.com

服務(wù)器:hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "net" "fmt")func main() { // 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)}

客戶端:hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "net" "fmt")func main() { // 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))}

服務(wù)器從任何客戶端讀取消息并發(fā)送響應(yīng)。客戶端發(fā)送消息并等待響應(yīng)。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 3:并發(fā) TCP 服務(wù)器

并發(fā)允許同時(shí)處理多個(gè)客戶端。hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "net" "fmt")func main() { // 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) }}func handleConnection(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!"))}

通過為每個(gè)連接使用新的 goroutine,多個(gè)客戶端可以同時(shí)連接。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 4:帶有 Gorilla Mux 的 HTTP 服務(wù)器

Gorilla Mux 庫簡化了 HTTP 請求路由。hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "fmt" "github.com/gorilla/mux" "net/http")func main() { // Create a new router. r := mux.NewRouter() // Register a handler function for the root path. r.HandleFunc("/", homeHandler) http.ListenAndServe(":8080", r)}func homeHandler(w http.ResponseWriter, r *http.Request) { // Respond with a welcome message. fmt.Fprint(w, "Welcome to Home!")}

這段代碼設(shè)置了一個(gè) HTTP 服務(wù)器,并為根路徑定義了一個(gè)處理函數(shù)。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 5:HTTPS 服務(wù)器

實(shí)現(xiàn) HTTPS 服務(wù)器可以確保安全通信。hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "net/http" "log")func main() { 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))}

服務(wù)器使用 TLS(傳輸層安全性)來加密通信。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 6:自定義 TCP 協(xié)議

可以使用自定義的 TCP 協(xié)議進(jìn)行專門的通信。hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "net" "strings")func main() { // 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) }}func handleConnection(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")) }}

這段代碼實(shí)現(xiàn)了一個(gè)簡單的自定義協(xié)議,當(dāng)客戶端發(fā)送命令“TIME”時(shí),它會回復(fù)當(dāng)前時(shí)間。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 7:使用 Gorilla WebSocket 進(jìn)行 WebSockets

WebSockets 提供了通過單一連接的實(shí)時(shí)全雙工通信。hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "github.com/gorilla/websocket" "net/http")var upgrader = websocket.Upgrader{ ReadBufferSize:  1024, WriteBufferSize: 1024,}func handler(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil {  http.Error(w, "Could not open websocket connection", http.StatusBadRequest)  return } defer conn.Close() for {  messageType, p, err := conn.ReadMessage()  if err != nil {   return  }  // Echo the message back to the client.  conn.WriteMessage(messageType, p) }}func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil)}

WebSocket 服務(wù)器會將消息回傳給客戶端。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 8:連接超時(shí)

可以使用 context 包來管理連接超時(shí)。hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "context" "fmt" "net" "time")func main() { // Create a context with a timeout of 2 seconds ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // Dialer using the context dialer := net.Dialer{} conn, err := dialer.DialContext(ctx, "tcp", "localhost:8080") if err != nil {  panic(err) } buffer := make([]byte, 1024) _, err = conn.Read(buffer) if err == nil {  fmt.Println("Received:", string(buffer)) } else {  fmt.Println("Connection error:", err) }}

這段代碼為從連接讀取數(shù)據(jù)設(shè)置了兩秒的截止時(shí)間。hyF28資訊網(wǎng)——每日最新資訊28at.com

示例 9:使用 golang.org/x/time/rate 進(jìn)行速率限制

速率限制控制請求的速率。hyF28資訊網(wǎng)——每日最新資訊28at.com

package mainimport ( "golang.org/x/time/rate" "net/http" "time")// Define a rate limiter allowing two requests per second with a burst capacity of five.var limiter = rate.NewLimiter(2, 5)func handler(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!"))}func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil)}

此示例使用速率限制器,將請求速率限制為每秒兩個(gè)請求,突發(fā)容量為五個(gè)。hyF28資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-17249-0.htmlGo 語言高級網(wǎng)絡(luò)編程

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com

上一篇: 如何精確控制 asyncio 中并發(fā)運(yùn)行的多個(gè)任務(wù)

下一篇: 如何將Docker的構(gòu)建時(shí)間減少40%

標(biāo)簽:
  • 熱門焦點(diǎn)
  • 7月安卓手機(jī)性價(jià)比榜:努比亞+紅魔兩款新機(jī)入榜

    7月登場的新機(jī)有努比亞Z50S Pro和紅魔8S Pro,除了三星之外目前唯二的兩款搭載超頻版驍龍8Gen2處理器的產(chǎn)品,而且努比亞和紅魔也一貫有著不錯的性價(jià)比,所以在本次的性價(jià)比榜單
  • 得物效率前端微應(yīng)用推進(jìn)過程與思考

    一、背景效率工程隨著業(yè)務(wù)的發(fā)展,組織規(guī)模的擴(kuò)大,越來越多的企業(yè)開始意識到協(xié)作效率對于企業(yè)團(tuán)隊(duì)的重要性,甚至是決定其在某個(gè)行業(yè)競爭中突圍的關(guān)鍵,是企業(yè)長久生存的根本。得物
  • 多線程開發(fā)帶來的問題與解決方法

    使用多線程主要會帶來以下幾個(gè)問題:(一)線程安全問題  線程安全問題指的是在某一線程從開始訪問到結(jié)束訪問某一數(shù)據(jù)期間,該數(shù)據(jù)被其他的線程所修改,那么對于當(dāng)前線程而言,該線程
  • Temu起訴SHEIN,跨境電商戰(zhàn)事升級

    來源 | 伯虎財(cái)經(jīng)(bohuFN)作者 | 陳平安日前據(jù)外媒報(bào)道,拼多多旗下跨境電商平臺Temu正對競爭對手SHEIN提起新訴訟,訴狀稱Shein“利用市場支配力量強(qiáng)迫服裝廠商與之簽訂獨(dú)家
  • 拼多多APP上線本地生活入口,群雄逐鹿萬億市場

    Tech星球(微信ID:tech618)文 | 陳橋輝 Tech星球獨(dú)家獲悉,拼多多在其APP內(nèi)上線了“本地生活”入口,位置較深,位于首頁的“充值中心”內(nèi),目前主要售賣美食相關(guān)的
  • 小米MIX Fold 3下月亮相:今年唯一無短板的全能折疊屏

    這段時(shí)間以來,包括三星、一加、榮耀等等有不少品牌旗下的最新折疊屏旗艦都有新的進(jìn)展,其中榮耀、三星都已陸續(xù)發(fā)布了最新的折疊屏旗艦,尤其號榮耀Magi
  • 上海舉辦人工智能大會活動,建設(shè)人工智能新高地

    人工智能大會在上海浦江兩岸隆重拉開帷幕,人工智能新技術(shù)、新產(chǎn)品、新應(yīng)用、新理念集中亮相。8月30日晚,作為大會的特色活動之一的上海人工智能發(fā)展盛典人工
  • “買真退假” 這種“羊毛”不能薅

    □ 法治日報(bào) 記者 王春   □ 本報(bào)通訊員 胡佳麗  2020年初,還在上大學(xué)的小東加入了一個(gè)大學(xué)生兼職QQ群。群主“七王”在群里介紹一些刷單賺
  • 北京:科技教育體驗(yàn)基地開始登記

      北京“科技館之城”科技教育體驗(yàn)基地登記和認(rèn)證工作日前啟動。首批北京科技教育體驗(yàn)基地?cái)M于2023年全國科普日期間掛牌,后續(xù)還將開展常態(tài)化登記。  北京科技教育體驗(yàn)基
Top 主站蜘蛛池模板: 友谊县| 锦屏县| 锡林浩特市| 阳山县| 上虞市| 泸溪县| 兖州市| 富平县| 广南县| 长丰县| 阳高县| 三亚市| 祁门县| 封开县| 宁安市| 涟源市| 三江| 七台河市| 凤翔县| 泾川县| 明水县| 尚志市| 抚远县| 松江区| 苏尼特左旗| 武宁县| 慈利县| 江安县| 普安县| 临泽县| 琼结县| 邵东县| 剑阁县| 兴国县| 三江| 抚州市| 玉门市| 苏尼特左旗| 芦山县| 秦安县| 偃师市|