溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

golang網絡socket粘包問題的解決方法

發布時間:2020-08-27 00:36:53 來源:腳本之家 閱讀:305 作者:dotcoo 欄目:編程語言

本文實例講述了golang網絡socket粘包問題的解決方法。分享給大家供大家參考,具體如下:

看到很多人問這個問題, 今天就寫了個例子, 希望能幫助大家

首先說一下什么是粘包:百度上比較通俗的說法是指TCP協議中,發送方發送的若干包數據到接收方接收時粘成一包,從接收緩沖區看,后一包數據的頭緊接著前一包數據的尾。

解決方案如下:

服務端:

復制代碼 代碼如下:
package main
import (
    "bytes"
    "encoding/binary"
    "fmt"
    "io"
    "net"
)
func main() {
    // 監聽端口
    ln, err := net.Listen("tcp", ":6000")
    if err != nil {
        fmt.Printf("Listen Error: %s\n", err)
        return
    }
    // 監聽循環
    for {
        // 接受客戶端鏈接
        conn, err := ln.Accept()
        if err != nil {
            fmt.Printf("Accept Error: %s\n", err)
            continue
        }
        // 處理客戶端鏈接
        go handleConnection(conn)
    }
}
func handleConnection(conn net.Conn) {
    // 關閉鏈接
    defer conn.Close()
    // 客戶端
    fmt.Printf("Client: %s\n", conn.RemoteAddr())
    // 消息緩沖
    msgbuf := bytes.NewBuffer(make([]byte, 0, 10240))
    // 數據緩沖
    databuf := make([]byte, 4096)
    // 消息長度
    length := 0
    // 消息長度uint32
    ulength := uint32(0)
    // 數據循環
    for {
        // 讀取數據
        n, err := conn.Read(databuf)
        if err == io.EOF {
            fmt.Printf("Client exit: %s\n", conn.RemoteAddr())
        }
        if err != nil {
            fmt.Printf("Read error: %s\n", err)
            return
        }
        fmt.Println(databuf[:n])
        // 數據添加到消息緩沖
        n, err = msgbuf.Write(databuf[:n])
        if err != nil {
            fmt.Printf("Buffer write error: %s\n", err)
            return
        }
        // 消息分割循環
        for {
            // 消息頭
            if length == 0 && msgbuf.Len() >= 4 {
                binary.Read(msgbuf, binary.LittleEndian, &ulength)
                length = int(ulength)
                // 檢查超長消息
                if length > 10240 {
                    fmt.Printf("Message too length: %d\n", length)
                    return
                }
            }
            // 消息體
            if length > 0 && msgbuf.Len() >= length {
                fmt.Printf("Client messge: %s\n", string(msgbuf.Next(length)))
                length = 0
            } else {
                break
            }
        }
    }
}

客戶端:

復制代碼 代碼如下:
package main
import (
    "bytes"
    "encoding/binary"
    "fmt"
    "net"
    "time"
)
func main() {
    // 鏈接服務器
    conn, err := net.Dial("tcp", "127.0.0.1:6000")
    if err != nil {
        fmt.Printf("Dial error: %s\n", err)
        return
    }
    // 客戶端信息
    fmt.Printf("Client: %s\n", conn.LocalAddr())
    // 消息緩沖
    msgbuf := bytes.NewBuffer(make([]byte, 0, 1024))
    // 消息內容
    message := []byte("我是utf-8的消息")
    // 消息長度
    messageLen := uint32(len(message))
    // 消息總長度
    mlen := 4 + len(message)
    // 寫入5條消息
    for i := 0; i < 10; i++ {
        binary.Write(msgbuf, binary.LittleEndian, messageLen)
        msgbuf.Write(message)
    }
    // 單包發送一條消息
    conn.Write(msgbuf.Next(mlen))
    time.Sleep(time.Second)
    // 單包發送三條消息
    conn.Write(msgbuf.Next(mlen * 3))
    time.Sleep(time.Second)
    // 發送不完整的消息頭
    conn.Write(msgbuf.Next(2))
    time.Sleep(time.Second)
    // 發送消息剩下部分
    conn.Write(msgbuf.Next(mlen - 2))
    time.Sleep(time.Second)
    // 發送不完整的消息體
    conn.Write(msgbuf.Next(mlen - 6))
    time.Sleep(time.Second)
    // 發送消息剩下部分
    conn.Write(msgbuf.Next(6))
    time.Sleep(time.Second)
    // 多段發送
    conn.Write(msgbuf.Next(mlen + 2))
    time.Sleep(time.Second)
    conn.Write(msgbuf.Next(-2 + mlen - 8))
    time.Sleep(time.Second)
    conn.Write(msgbuf.Next(8 + 1))
    time.Sleep(time.Second)
    conn.Write(msgbuf.Next(-1 + mlen + mlen))
    time.Sleep(time.Second)
    // 關閉鏈接
    conn.Close()
}

希望本文所述對大家Go語言程序設計有所幫助。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女