mux.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package yamux
  2. import (
  3. "fmt"
  4. "io"
  5. "time"
  6. )
  7. // Config is used to tune the Yamux session
  8. type Config struct {
  9. // AcceptBacklog is used to limit how many streams may be
  10. // waiting an accept.
  11. AcceptBacklog int
  12. // EnableCompression is used to control if we compress
  13. // outgoing data. We have no control over incoming data.
  14. EnableCompression bool
  15. // EnableKeepalive is used to do a period keep alive
  16. // messages using a ping.
  17. EnableKeepAlive bool
  18. // KeepAliveInterval is how often to perform the keep alive
  19. KeepAliveInterval time.Duration
  20. // MaxStreamWindowSize is used to control the maximum
  21. // window size that we allow for a stream.
  22. MaxStreamWindowSize uint32
  23. }
  24. // DefaultConfig is used to return a default configuration
  25. func DefaultConfig() *Config {
  26. return &Config{
  27. AcceptBacklog: 256,
  28. EnableCompression: true,
  29. EnableKeepAlive: true,
  30. KeepAliveInterval: 30 * time.Second,
  31. MaxStreamWindowSize: initialStreamWindow,
  32. }
  33. }
  34. // VerifyConfig is used to verify the sanity of configuration
  35. func VerifyConfig(config *Config) error {
  36. if config.AcceptBacklog <= 0 {
  37. return fmt.Errorf("backlog must be positive")
  38. }
  39. if config.KeepAliveInterval == 0 {
  40. return fmt.Errorf("keep-alive interval must be positive")
  41. }
  42. if config.MaxStreamWindowSize < initialStreamWindow {
  43. return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow)
  44. }
  45. return nil
  46. }
  47. // Server is used to initialize a new server-side connection.
  48. // There must be at most one server-side connection. If a nil config is
  49. // provided, the DefaultConfiguration will be used.
  50. func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
  51. if config == nil {
  52. config = DefaultConfig()
  53. }
  54. if err := VerifyConfig(config); err != nil {
  55. return nil, err
  56. }
  57. return newSession(config, conn, false), nil
  58. }
  59. // Client is used to initialize a new client-side connection.
  60. // There must be at most one client-side connection.
  61. func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) {
  62. if config == nil {
  63. config = DefaultConfig()
  64. }
  65. if err := VerifyConfig(config); err != nil {
  66. return nil, err
  67. }
  68. return newSession(config, conn, true), nil
  69. }