Skip to content

eleztian/toh

Repository files navigation

TOH Project

TOH (Tcp Over HTTP) is a Go library that enables TCP communication over HTTP. It allows clients to establish connections to servers and transfer data between them via HTTP requests.

Installation

Make sure you have Go installed. Then run:

go get github.com/eleztian/toh

Usage

Create a TCP Server

Create a TCP server that handles client connections and echoes received data.

func main() {
    s := toh.NewTcpServer(context.Background(), "tcp", nil)
    defer s.Close()

    smux := http.NewServeMux()
    smux.Handle("/tcp", s)

    go func() {
        err := http.ListenAndServe("0.0.0.0:8083", smux)
        if err != nil {
            panic(err)
        }
    }()

    for {
        conn, err := s.Accept()
        if err != nil {
            return
        }
        go func() {
            defer func() { _ = conn.Close() }()

            for {
                data := make([]byte, 1024)
                n, err := conn.Read(data)
                if err != nil {
                    return
                }
                _, _ = conn.Write(data[:n])
            }
        }()
    }
}

Connect to TCP Server

Use toh.Dial to connect to a remote server and send/receive data.

func main() {
    conn, err := toh.Dial(http.MethodGet, "http://127.0.0.1/kp/tcp")
    if err != nil {
        panic(err)
    }
    
    for {
        conn.Write([]byte("hello"))
        data := make([]byte, 1024)
        n, err := conn.Read(data)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(data[:n]))
        time.Sleep(time.Second)
    }
}

About

tcp over http

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages