yamux多路複用的使用例子

yamux

yamux 是一個多路複用庫。它依賴於底層可靠有序鏈接。如TCP. 提供基於流的多路利用git

例子以下:
Servergithub

package main
// 多路複用
import (
    "fmt"
    "github.com/hashicorp/yamux"
    "net"
    "time"
)

func Recv(stream net.Conn, id int){
    for {
        buf := make([]byte, 4)
        n, err := stream.Read(buf)
        if err == nil{
            fmt.Println("ID:", id, ", len:", n, time.Now().Unix(), string(buf))
        }else{
            fmt.Println(time.Now().Unix(), err)
            return
        }
    }
}
func main()  {
    // 創建底層複用鏈接
    tcpaddr, _ := net.ResolveTCPAddr("tcp4", "127.0.0.1:8980");
    tcplisten, _ := net.ListenTCP("tcp", tcpaddr);
    conn, _ := tcplisten.Accept()
    session, _ := yamux.Server(conn, nil)

    id :=1
    for {
        // 創建多個流通路
        stream, err := session.Accept()
        if err == nil {
            fmt.Println("accept")
            id ++
            go Recv(stream, id)
        }else{
            fmt.Println("session over.")
            return
        }
    }

}

Clientsession

package main

import (
    "github.com/hashicorp/yamux"
    "net"
    "time"
)

func main()  {
    // 創建底層複用通道
    conn, _ := net.Dial("tcp", "127.0.0.1:8980")
    session, _ := yamux.Client(conn, nil)

    // 創建應用流通道1
    stream, _ := session.Open()
    stream.Write([]byte("ping" ))
    stream.Write([]byte("pnng" ))
    time.Sleep(1 * time.Second)

    // 創建應用流通道2
    stream1, _ := session.Open()
    stream1.Write([]byte("pong"))
    time.Sleep(1 * time.Second)

    // 清理退出
    time.Sleep(5 * time.Second)
    stream.Close()
    stream1.Close()
    session.Close()
    conn.Close()
}
相關文章
相關標籤/搜索