0

I'm trying to implement the RTMP protocol to along side my web application in Go, however I can't seem to figure out solution to handle both HTTP and and RTMP on the same port.

The idea would be something such as this.

package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, "Hello!")
    })

    http.HandleFunc("/rtmp", func(w http.ResponseWriter, r *http.Request) {
        // RTMP handling here
    })

    fmt.Println("Starting web server")
    http.ListenAndServe(":8000", nil)
}

zhangpeihao/gortmp has a great RMTP module with an example that shows handling RTMP by listening on a TCP socket. However how can handle it on a specific endpoint rather then a second port?

2
  • 1
    I'm guessing you need to tunnel RTMP over HTTP Oct 31, 2016 at 17:41
  • Aside from tunnelling protocols within other protocols, it's unusual to serve more than one protocol per port. I imagine that some solution would involve peeking at the first few bytes received until you can decide which handler to employ. I've never seen this attempted.
    – Rick-777
    Nov 4, 2016 at 22:32

1 Answer 1

0

While wanting to avoid having to convert RTMPT to RTMP, and without having to fork other modules, this was my solution in the end by reading the first byte. Full implementation can be found here.

func createLocalConnection(port string) *net.TCPConn {
    addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:"+port)
    if err != nil {
        panic(err)
    }
    conn, err := net.DialTCP("tcp", nil, addr)
    if err != nil {
        panic(err)
    }
    return conn
}

func proxyConnection(conn *net.TCPConn) {
  defer conn.Close()
  data := make([]byte, 1)
  n, err := conn.Read(data)
  if err != nil {
    fmt.Println(err)
    return
  }

  var proxyConn *net.TCPConn
  if data[0] == 0x03 { // RTMP first byte.
    proxyConn = createLocalConnection(RTMPPort)
  } else {
    proxyConn = createLocalConnection(HTTPPort)
  }
  proxyConn.Write(data[:n])
  defer proxyConn.Close()

  // Request loop
  go func() {
    for {
      data := make([]byte, 1024*1024)
      n, err := conn.Read(data)
      if err != nil {
        break
      }
      proxyConn.Write(data[:n])
    }
  }()

  // Response loop
  for {
    data := make([]byte, 1024*1024)
    n, err := proxyConn.Read(data)
    if err != nil {
      break
    }
    conn.Write(data[:n])
  }
}

func main() {
  listener, err := net.ListenTCP("tcp", addr)
    if err != nil {
        panic(err)
    }

  for {
    conn, err := listener.AcceptTCP()
    if err != nil {
      fmt.Println(err)
      continue
    }

    go server.ProxyConnection(conn)
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.