1
0

mux.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package smux
  2. import (
  3. "fmt"
  4. "io"
  5. "time"
  6. "github.com/pkg/errors"
  7. )
  8. // Config is used to tune the Smux session
  9. type Config struct {
  10. // KeepAliveInterval is how often to send a NOP command to the remote
  11. KeepAliveInterval time.Duration
  12. // KeepAliveTimeout is how long the session
  13. // will be closed if no data has arrived
  14. KeepAliveTimeout time.Duration
  15. // MaxFrameSize is used to control the maximum
  16. // frame size to sent to the remote
  17. MaxFrameSize int
  18. // MaxReceiveBuffer is used to control the maximum
  19. // number of data in the buffer pool
  20. MaxReceiveBuffer int
  21. }
  22. // DefaultConfig is used to return a default configuration
  23. func DefaultConfig() *Config {
  24. return &Config{
  25. KeepAliveInterval: 10 * time.Second,
  26. KeepAliveTimeout: 30 * time.Second,
  27. MaxFrameSize: 4096,
  28. MaxReceiveBuffer: 4194304,
  29. }
  30. }
  31. // VerifyConfig is used to verify the sanity of configuration
  32. func VerifyConfig(config *Config) error {
  33. if config.KeepAliveInterval == 0 {
  34. return errors.New("keep-alive interval must be positive")
  35. }
  36. if config.KeepAliveTimeout < config.KeepAliveInterval {
  37. return fmt.Errorf("keep-alive timeout must be larger than keep-alive interval")
  38. }
  39. if config.MaxFrameSize <= 0 {
  40. return errors.New("max frame size must be positive")
  41. }
  42. if config.MaxFrameSize > 65535 {
  43. return errors.New("max frame size must not be larger than 65535")
  44. }
  45. if config.MaxReceiveBuffer <= 0 {
  46. return errors.New("max receive buffer must be positive")
  47. }
  48. return nil
  49. }
  50. // Server is used to initialize a new server-side connection.
  51. func Server(conn io.ReadWriteCloser, config *Config) (*Session, error) {
  52. if config == nil {
  53. config = DefaultConfig()
  54. }
  55. if err := VerifyConfig(config); err != nil {
  56. return nil, err
  57. }
  58. return newSession(config, conn, false), nil
  59. }
  60. // Client is used to initialize a new 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. }