mux.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // EnableKeepalive is used to do a period keep alive
  13. // messages using a ping.
  14. EnableKeepAlive bool
  15. // KeepAliveInterval is how often to perform the keep alive
  16. KeepAliveInterval time.Duration
  17. // MaxStreamWindowSize is used to control the maximum
  18. // window size that we allow for a stream.
  19. MaxStreamWindowSize uint32
  20. }
  21. // DefaultConfig is used to return a default configuration
  22. func DefaultConfig() *Config {
  23. return &Config{
  24. AcceptBacklog: 256,
  25. EnableKeepAlive: true,
  26. KeepAliveInterval: 30 * time.Second,
  27. MaxStreamWindowSize: initialStreamWindow,
  28. }
  29. }
  30. // VerifyConfig is used to verify the sanity of configuration
  31. func VerifyConfig(config *Config) error {
  32. if config.AcceptBacklog <= 0 {
  33. return fmt.Errorf("backlog must be positive")
  34. }
  35. if config.KeepAliveInterval == 0 {
  36. return fmt.Errorf("keep-alive interval must be positive")
  37. }
  38. if config.MaxStreamWindowSize < initialStreamWindow {
  39. return fmt.Errorf("MaxStreamWindowSize must be larger than %d", initialStreamWindow)
  40. }
  41. return nil
  42. }
  43. // Server is used to initialize a new server-side connection.
  44. // There must be at most one server-side connection. If a nil config is
  45. // provided, the DefaultConfiguration will be used.
  46. func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
  47. if config == nil {
  48. config = DefaultConfig()
  49. }
  50. if err := VerifyConfig(config); err != nil {
  51. return nil, err
  52. }
  53. return newSession(config, conn, false), nil
  54. }
  55. // Client is used to initialize a new client-side connection.
  56. // There must be at most one client-side connection.
  57. func Client(conn io.ReadWriteCloser, config *Config) (*Session, error) {
  58. if config == nil {
  59. config = DefaultConfig()
  60. }
  61. if err := VerifyConfig(config); err != nil {
  62. return nil, err
  63. }
  64. return newSession(config, conn, true), nil
  65. }