| 1 |
package muxado |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/tls" |
| 5 |
"github.com/inconshreveable/muxado/proto" |
| 6 |
"github.com/inconshreveable/muxado/proto/ext" |
| 7 |
"net" |
| 8 |
) |
| 9 |
|
| 10 |
// A Listener accepts new connections from its net.Listener |
| 11 |
// and begins muxado server connections on them. |
| 12 |
// |
| 13 |
// It's API is very similar to a net.Listener, but it returns |
| 14 |
// muxado.Sessions instead of net.Conn's. |
| 15 |
type Listener struct { |
| 16 |
wrapped net.Listener |
| 17 |
} |
| 18 |
|
| 19 |
// Accept the next connection from the listener and begin |
| 20 |
// a muxado session on it. |
| 21 |
func (l *Listener) Accept() (Session, error) { |
| 22 |
conn, err := l.wrapped.Accept() |
| 23 |
if err != nil { |
| 24 |
return nil, err |
| 25 |
} |
| 26 |
|
| 27 |
return Server(conn), nil |
| 28 |
} |
| 29 |
|
| 30 |
// Addr returns the bound address of the wrapped net.Listener |
| 31 |
func (l *Listener) Addr() net.Addr { |
| 32 |
return l.wrapped.Addr() |
| 33 |
} |
| 34 |
|
| 35 |
// Close closes the wrapped net.Listener |
| 36 |
func (l *Listener) Close() error { |
| 37 |
return l.wrapped.Close() |
| 38 |
} |
| 39 |
|
| 40 |
// Server returns a muxado server session using conn as the transport. |
| 41 |
func Server(conn net.Conn) Session { |
| 42 |
return &sessionAdaptor{proto.NewSession(conn, proto.NewStream, false, []proto.Extension{ext.NewDefaultHeartbeat()})} |
| 43 |
} |
| 44 |
|
| 45 |
// Listen binds to a network address and returns a Listener which accepts |
| 46 |
// new connections and starts muxado server sessions on them. |
| 47 |
func Listen(network, addr string) (*Listener, error) { |
| 48 |
l, err := net.Listen(network, addr) |
| 49 |
if err != nil { |
| 50 |
return nil, err |
| 51 |
} |
| 52 |
|
| 53 |
return &Listener{l}, nil |
| 54 |
} |
| 55 |
|
| 56 |
// ListenTLS binds to a network address and accepts new TLS-encrypted connections. |
| 57 |
// It returns a Listener which starts new muxado server sessions on the connections. |
| 58 |
func ListenTLS(network, addr string, tlsConfig *tls.Config) (*Listener, error) { |
| 59 |
l, err := tls.Listen(network, addr, tlsConfig) |
| 60 |
if err != nil { |
| 61 |
return nil, err |
| 62 |
} |
| 63 |
|
| 64 |
return &Listener{l}, nil |
| 65 |
} |
| 66 |
|
| 67 |
// NewListener creates a new muxado listener which creates new muxado server sessions |
| 68 |
// by accepting connections from the given net.Listener |
| 69 |
func NewListener(l net.Listener) *Listener { |
| 70 |
return &Listener{l} |
| 71 |
} |