当前位置:首页 > 科技  > 软件

Go 语言高级网络编程

来源: 责编: 时间:2023-11-06 17:18:54 344观看
导读一、简介Go(Golang)中的网络编程具有易用性、强大性和乐趣。本指南深入探讨了网络编程的复杂性,涵盖了协议、TCP/UDP 套接字、并发等方面的内容,并附有详细的注释。二、关键概念1. 网络协议TCP(传输控制协议):确保可靠的数据

一、简介

Go(Golang)中的网络编程具有易用性、强大性和乐趣。本指南深入探讨了网络编程的复杂性,涵盖了协议、TCP/UDP 套接字、并发等方面的内容,并附有详细的注释。Bse28资讯网——每日最新资讯28at.com

Bse28资讯网——每日最新资讯28at.com

二、关键概念

1. 网络协议

  • TCP(传输控制协议):确保可靠的数据传输。
  • UDP(用户数据报协议):更快,但不保证数据传递。

2. 套接字

  • TCP 套接字:用于面向连接的通信。
  • UDP 套接字:用于无连接通信。

3. 并发

  • Goroutines(协程):允许在代码中实现并行处理。
  • Channels(通道):用于协程之间的通信。

三、示例

示例 1:TCP 服务器和客户端

TCP 服务器和客户端示例演示了TCP通信的基础。Bse28资讯网——每日最新资讯28at.com

服务器:Bse28资讯网——每日最新资讯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)))}

客户端:Bse28资讯网——每日最新资讯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))}

服务器在端口8080上等待连接,读取传入的消息并发送响应。客户端连接到服务器,发送消息并打印服务器的响应。Bse28资讯网——每日最新资讯28at.com

示例 2:UDP 服务器和客户端

与TCP不同,UDP是无连接的。以下是UDP服务器和客户端的实现。Bse28资讯网——每日最新资讯28at.com

服务器:Bse28资讯网——每日最新资讯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)}

客户端:Bse28资讯网——每日最新资讯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))}

服务器从任何客户端读取消息并发送响应。客户端发送消息并等待响应。Bse28资讯网——每日最新资讯28at.com

示例 3:并发 TCP 服务器

并发允许同时处理多个客户端。Bse28资讯网——每日最新资讯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!"))}

通过为每个连接使用新的 goroutine,多个客户端可以同时连接。Bse28资讯网——每日最新资讯28at.com

示例 4:带有 Gorilla Mux 的 HTTP 服务器

Gorilla Mux 库简化了 HTTP 请求路由。Bse28资讯网——每日最新资讯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!")}

这段代码设置了一个 HTTP 服务器,并为根路径定义了一个处理函数。Bse28资讯网——每日最新资讯28at.com

示例 5:HTTPS 服务器

实现 HTTPS 服务器可以确保安全通信。Bse28资讯网——每日最新资讯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))}

服务器使用 TLS(传输层安全性)来加密通信。Bse28资讯网——每日最新资讯28at.com

示例 6:自定义 TCP 协议

可以使用自定义的 TCP 协议进行专门的通信。Bse28资讯网——每日最新资讯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")) }}

这段代码实现了一个简单的自定义协议,当客户端发送命令“TIME”时,它会回复当前时间。Bse28资讯网——每日最新资讯28at.com

示例 7:使用 Gorilla WebSocket 进行 WebSockets

WebSockets 提供了通过单一连接的实时全双工通信。Bse28资讯网——每日最新资讯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 服务器会将消息回传给客户端。Bse28资讯网——每日最新资讯28at.com

示例 8:连接超时

可以使用 context 包来管理连接超时。Bse28资讯网——每日最新资讯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) }}

这段代码为从连接读取数据设置了两秒的截止时间。Bse28资讯网——每日最新资讯28at.com

示例 9:使用 golang.org/x/time/rate 进行速率限制

速率限制控制请求的速率。Bse28资讯网——每日最新资讯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)}

此示例使用速率限制器,将请求速率限制为每秒两个请求,突发容量为五个。Bse28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-17249-0.htmlGo 语言高级网络编程

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 如何精确控制 asyncio 中并发运行的多个任务

下一篇: 如何将Docker的构建时间减少40%

标签:
  • 热门焦点
  • K60 Pro官方停产 第三方瞬间涨价

    虽然没有官方宣布,但Redmi的一些高管也已经透露了,Redmi K60 Pro已经停产且不会补货,这一切都是为了即将到来的K60 Ultra铺路,属于厂家的正常操作。但有意思的是该机在停产之后
  • 俄罗斯:将审查iPhone等外国公司设备 保数据安全

    iPhone和特斯拉都属于在各自领域领头羊的品牌,推出的产品也也都是数一数二的,但对于一些国家而言,它们的产品可靠性和安全性还是在限制范围内。近日,俄罗斯联邦通信、信息技术
  • 影音体验是真的强 简单聊聊iQOO Pad

    大公司的好处就是产品线丰富,非常细分化的东西也能给你做出来,例如早先我们看到了新的vivo Pad2,之后我们又在iQOO Neo8 Pro的发布会上看到了iQOO的首款平板产品iQOO Pad。虽
  • 6月安卓手机好评榜:魅族20 Pro蝉联冠军

    性能榜和性价比榜之后,我们来看最后的安卓手机好评榜,数据来源安兔兔评测,收集时间2023年6月1日至6月30日,仅限国内市场。第一名:魅族20 Pro好评率:95%5月份的时候魅族20 Pro就是
  • 跑分安卓第一!Redmi K60至尊版8月发布!卢伟冰:目标年度性能之王

    8月5日消息,Redmi K60至尊版将于8月发布,在此前举行的战略发布会上,官方该机将搭载搭载天玑9200+处理器,安兔兔V10跑分超177万分,是目前安卓阵营最高的分数
  • 把LangChain跑起来的三个方法

    使用LangChain开发LLM应用时,需要机器进行GLM部署,好多同学第一步就被劝退了,那么如何绕过这个步骤先学习LLM模型的应用,对Langchain进行快速上手?本片讲解3个把LangChain跑起来
  • 三万字盘点 Spring 九大核心基础功能

    大家好,我是三友~~今天来跟大家聊一聊Spring的9大核心基础功能。话不多说,先上目录:图片友情提示,本文过长,建议收藏,嘿嘿嘿!一、资源管理资源管理是Spring的一个核心的基础功能,不
  • 破圈是B站头上的紧箍咒

    来源 | 光子星球撰文 | 吴坤谚编辑 | 吴先之每年的暑期档都少不了瞄准追剧女孩们的古偶剧集,2021年有优酷的《山河令》,2022年有爱奇艺的《苍兰诀》,今年却轮到小破站抓住了追
  • 年轻人的“职场羞耻感”,无处不在

    作者:冯晓亭 陶 淘 李 欣 张 琳 马舒叶来源:燃次元“人在职场,应该选择什么样的着装?”近日,在网络上,一个与着装相关的帖子引发关注,在该帖子里,一位在高级写字楼亚洲金
Top