• go模拟网络数据包传送代码


    1.构建数据包过程

    package protocol
    
    import (
        "bufio"
        "bytes"
        "encoding/binary"
        "fmt"
    )
    
    //构建网络中数据包格式
    func Encode (message string ) []byte {
        var length = int32(len(message))
        var pkg = new(bytes.Buffer)
        err:=binary.Write(pkg,binary.LittleEndian,length)//前四个字节
        if err != nil {
            fmt.Println("build pkg is error")
            return nil
        }
        err=binary.Write(pkg,binary.LittleEndian,[]byte(message))
        if err != nil {
            return nil
        }
        return pkg.Bytes()
    }
    //解包过程
    func Decode( reader *bufio.Reader) string {
        lengthBytes,_:= reader.Peek(4)//前4个字节数据
        lengthBuff:=bytes.NewBuffer(lengthBytes)
        var length int32
        binary.Read(lengthBuff,binary.LittleEndian,&length)
    
        //if int32(reader.Buffered()) < length +4 {
        //    return nil
        //}
    
        pack:=make([]byte, int(4+length))
        reader.Read(pack)
        return string(pack[4:])
    
    }

    1.服务端

    package main
    
    import (
        "bufio"
        "fmt"
        "net"
        "protocol"
    )
    
    func process(conn net.Conn){
        defer conn.Close()
        reader:=bufio.NewReader(conn)
        for {
            msg:= protocol.Decode(reader)
            fmt.Printf("%v\n",msg)
        }
    }
    
    func main(){
        listener,err:=net.Listen("tcp","127.0.0.1:8890")
        if err != nil {
            fmt.Println("start server is erros")
            return
        }
        for {
            conn,_:= listener.Accept()
            go process(conn)
        }
        defer listener.Close()
    }

    2.客户端

    package main
    
    import (
        "log"
        "net"
        "protocol"
        "time"
    )
    
    func main(){
        conn,err:=net.Dial("tcp","127.0.0.1:8890")
        if err != nil {
            log.Fatal("is error")
            return
        }
        str:="hello word你好"
        for i:=0;i<10;i++ {
            bytes:= protocol.Encode(str)
            conn.Write(bytes)
            time.Sleep(time.Second)
        }
    }
  • 相关阅读:
    Linux系统调用
    Kubernetes 中强化tab 功能
    Docker镜像构建之案例分享
    网络基础之名词介绍
    网络基础协议之UDP(下篇)
    网络基础协议之UDP(上篇)
    内核升级
    尼恩 Java高并发三部曲 [官方]
    CDN图解(秒懂
    DNS图解(秒懂
  • 原文地址:https://www.cnblogs.com/zh718594493/p/16259903.html
Copyright © 2020-2023  润新知