github.com/NebulousLabs/Sia@v1.3.7/modules/gateway/stream.go (about)

     1  package gateway
     2  
     3  import (
     4  	"net"
     5  
     6  	"github.com/NebulousLabs/Sia/build"
     7  	"github.com/xtaci/smux"
     8  )
     9  
    10  // A streamSession is a multiplexed transport that can accept or initiate
    11  // streams.
    12  type streamSession interface {
    13  	Accept() (net.Conn, error)
    14  	Open() (net.Conn, error)
    15  	Close() error
    16  }
    17  
    18  // newClientStream returns a new smux client.
    19  func newClientStream(conn net.Conn, version string) streamSession {
    20  	return newSmuxClient(conn)
    21  }
    22  
    23  // newServerStream returns a new smux server.
    24  func newServerStream(conn net.Conn, version string) streamSession {
    25  	return newSmuxServer(conn)
    26  }
    27  
    28  // smuxSession adapts the methods of smux.Session to conform to the
    29  // streamSession interface.
    30  type smuxSession struct {
    31  	sess *smux.Session
    32  }
    33  
    34  func (s smuxSession) Accept() (net.Conn, error) { return s.sess.AcceptStream() }
    35  func (s smuxSession) Open() (net.Conn, error)   { return s.sess.OpenStream() }
    36  func (s smuxSession) Close() error              { return s.sess.Close() }
    37  
    38  func newSmuxServer(conn net.Conn) streamSession {
    39  	sess, err := smux.Server(conn, nil) // default config means no error is possible
    40  	if err != nil {
    41  		build.Critical("smux should not fail with default config:", err)
    42  	}
    43  	return smuxSession{sess}
    44  }
    45  
    46  func newSmuxClient(conn net.Conn) streamSession {
    47  	sess, err := smux.Client(conn, nil) // default config means no error is possible
    48  	if err != nil {
    49  		build.Critical("smux should not fail with default config:", err)
    50  	}
    51  	return smuxSession{sess}
    52  }