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.
Make sure you have Go installed. Then run:
go get github.com/eleztian/tohCreate 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])
}
}()
}
}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)
}
}