Documentation
¶
Overview ¶
Package recws provides websocket client based on gorilla/websocket that will automatically reconnect if the connection is dropped.
Index ¶
- Constants
- Variables
- func Decode(b []byte) (data []interface{}, err error)
- func DistributedID() (string, error)
- func Encode(data interface{}) ([]byte, error)
- func EncodeMessage(msgType MsgType, requestId string, methodName string, authCode string, ...) (data []byte, err error)
- func IsPublic(name string) bool
- func IsPublicOrBuiltinType(t reflect.Type) bool
- func PrintStack()
- func RandStringRunes(n int) string
- func RefNew(refType reflect.Type) interface{}
- type AuthLevel
- type AuthObject
- type Client
- func (c *Client) Call(methodName string, response interface{}, inArgs ...interface{}) (err error)
- func (c *Client) CallWithWS(methodName string, inArgs ...interface{}) (res *Message, err error)
- func (c *Client) CloseServer() error
- func (c *Client) Subscribe(eventName string, filterString string) (subMsgChan <-chan []byte, subID int, err error)
- func (c *Client) UnSubscribe(eventName string, subID int) error
- func (c *Client) UnSubscribeAll() error
- type ClientOption
- func SetClientAUTH(token string) ClientOption
- func SetClientAttempts(attempts int) ClientOption
- func SetClientCache(cache httpcache.Cache) ClientOption
- func SetClientSleepTime(sleepTime time.Duration) ClientOption
- func SetClientTLS(config *tls.Config) ClientOption
- func SetClientTimeOut(timeout time.Duration) ClientOption
- func SetClientWS(maxMessageSize int, pingWait string, logger log.Logger) ClientOption
- type ClientOptions
- type ErrMsg
- type Errtype
- type Header
- type Message
- type MsgType
- type Option
- type Options
- type Queue
- type RecConn
- func (rc *RecConn) Close()
- func (rc *RecConn) CloseAndReconnect()
- func (rc *RecConn) Dial(urlStr string, reqHeader http.Header)
- func (rc *RecConn) GetDialError() error
- func (rc *RecConn) GetHTTPResponse() *http.Response
- func (rc *RecConn) GetURL() string
- func (rc *RecConn) IsConnected() bool
- func (rc *RecConn) ReadJSON(v interface{}) error
- func (rc *RecConn) ReadMessage() (messageType int, message []byte, err error)
- func (rc *RecConn) SetTLSClientConfig(tlsClientConfig *tls.Config)
- func (rc *RecConn) Shutdown(writeWait time.Duration)
- func (rc *RecConn) WriteJSON(v interface{}) error
- func (rc *RecConn) WriteMessage(messageType int, data []byte) error
- type RequestType
- type Server
- type WebsocketClient
- type WebsocketServer
Constants ¶
const HeadSize = 21
const StartCipher = 0x05 // 起始符
Variables ¶
var ( MaxSimultaneousTcpConn = 50 // max simultaneous Tcp connection for one Server MaxHttpHeaderBytes = 10 * 1024 // 10k MaxHttpBodyReaderBytes = 10 * 1024 // 10k HttpWriteTimeout = 10 * time.Second HttpReadHeaderTimeout = 5 * time.Second CertFilePath = "/mnt/c/Users/30640/Desktop/api_server/topia/api/rpc/example/test/server/server-cert.pem" // tmp test path KeyFilePath = "/mnt/c/Users/30640/Desktop/api_server/topia/api/rpc/example/test/server/server-key.pem" // tmp test path ClientMaxSubsToOneEvent = 5 // maximum times a client can subscribe to a single event simultaneously MaxSubQueueLength = 10 // maximum msgs for a single subscription queue to contain )
var ( ErrNonPublic = errors.New("registered non-public service") ErrNoAvailable = errors.New("no service is available, or provide service is not open") ErrCrc32 = errors.New("checksumIEEE error") ErrSerialization404 = errors.New("serialization 404") ErrCompressor404 = errors.New("compressor 404") ErrTimeout = errors.New("time out") ErrCircuitBreaker = errors.New("circuit breaker") ErrInput = errors.New("input error") ErrMethodNameRegister = errors.New("register method name error") ErrAuth = errors.New("auth error") ErrAuthLevel = errors.New("insufficient auth level") ErrMethodName = errors.New("method name error") )
var ErrNotConnected = errors.New("websocket: not connected")
ErrNotConnected is returned when the application read/writes a message and the connection is closed
Functions ¶
func DistributedID ¶
func EncodeMessage ¶
func EncodeMessage(msgType MsgType, requestId string, methodName string, authCode string, errMsg *ErrMsg, payload []byte) (data []byte, err error)
EncodeMessage 基础编码
func IsPublicOrBuiltinType ¶
func PrintStack ¶
func PrintStack()
func RandStringRunes ¶
Types ¶
type AuthObject ¶
type AuthObject struct {
// contains filtered or unexported fields
}
func NewAuthObject ¶
func NewAuthObject(m map[AuthLevel]string) *AuthObject
func (*AuthObject) Level ¶
func (auth *AuthObject) Level(token string) (authority AuthLevel)
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func NewClient ¶
func NewClient(addr string, options ...ClientOption) (*Client, error)
NewClient creates a new client
func (*Client) CallWithWS ¶
TODO 仅测试用
func (*Client) CloseServer ¶
func (*Client) UnSubscribeAll ¶
type ClientOption ¶
type ClientOption func(options *ClientOptions)
func SetClientAUTH ¶
func SetClientAUTH(token string) ClientOption
func SetClientAttempts ¶
func SetClientAttempts(attempts int) ClientOption
func SetClientCache ¶
func SetClientCache(cache httpcache.Cache) ClientOption
func SetClientSleepTime ¶
func SetClientSleepTime(sleepTime time.Duration) ClientOption
func SetClientTLS ¶
func SetClientTLS(config *tls.Config) ClientOption
func SetClientTimeOut ¶
func SetClientTimeOut(timeout time.Duration) ClientOption
func SetClientWS ¶
func SetClientWS(maxMessageSize int, pingWait string, logger log.Logger) ClientOption
using websocket
type ClientOptions ¶
type ClientOptions struct {
AUTH string
// contains filtered or unexported fields
}
type Errtype ¶
type Errtype int
const ( NoErr Errtype = 0 ErrMethodNotFound Errtype = 1 ErrAuthFailed Errtype = 2 ErrIllegalArgument Errtype = 3 ErrServiceReturnError Errtype = 4 // Error return by called service ErrNoSuchEvent Errtype = 5 ErrExceedMaxSubLimit Errtype = 6 // client is trying to sub one event for more than ClientMaxSubsToOneEvent ErrInvalidSubID Errtype = 7 ErrNoSuchSub Errtype = 8 )
type Header ¶
type Header struct {
Sc byte
RequestIdSize uint32
MethodNameSize uint32
AuthCodeSize uint32
ErrMsgSize uint32
PayloadSize uint32
}
func DecodeHeader ¶
type Message ¶
type Message struct {
Header *Header
MsgType MsgType
RequestId string // also used as subID when MsgType == MsgSubscribe
MethodName string // also used as eventName when MsgType is related to subscribe
AuthCode string
ErrMsg ErrMsg
Payload []byte
}
func DecodeMessageV2 ¶
type Option ¶
type Option func(options *Options)
func SetAUTH ¶
func SetAUTH(auth *AuthObject) Option
func SetEnableTLS ¶
func SetWebsocket ¶
type RecConn ¶
type RecConn struct {
// RecIntvlMin specifies the initial reconnecting interval,
// default to 2 seconds
RecIntvlMin time.Duration
// RecIntvlMax specifies the maximum reconnecting interval,
// default to 30 seconds
RecIntvlMax time.Duration
// RecIntvlFactor specifies the rate of increase of the reconnection
// interval, default to 1.5
RecIntvlFactor float64
// HandshakeTimeout specifies the duration for the handshake to complete,
// default to 2 seconds
HandshakeTimeout time.Duration
// Proxy specifies the proxy function for the dialer
// defaults to ProxyFromEnvironment
Proxy func(*http.Request) (*url.URL, error)
// Client TLS config to use on reconnect
TLSClientConfig *tls.Config
// SubscribeHandler fires after the connection successfully establish.
SubscribeHandler func() error
// KeepAliveTimeout is an interval for sending ping/pong messages
// disabled if 0
KeepAliveTimeout time.Duration
// NonVerbose suppress connecting/reconnecting messages.
NonVerbose bool
*websocket.Conn
// contains filtered or unexported fields
}
The RecConn type represents a Reconnecting WebSocket connection.
func (*RecConn) Close ¶
func (rc *RecConn) Close()
Close closes the underlying network connection without sending or waiting for a close frame.
func (*RecConn) CloseAndReconnect ¶
func (rc *RecConn) CloseAndReconnect()
CloseAndReconnect will try to reconnect.
func (*RecConn) Dial ¶
Dial creates a new client connection. The URL url specifies the host and request URI. Use requestHeader to specify the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). Use GetHTTPResponse() method for the response.Header to get the selected subprotocol (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
func (*RecConn) GetDialError ¶
GetDialError returns the last dialer error. nil on successful connection.
func (*RecConn) GetHTTPResponse ¶
GetHTTPResponse returns the http response from the handshake. Useful when WebSocket handshake fails, so that callers can handle redirects, authentication, etc.
func (*RecConn) IsConnected ¶
IsConnected returns the WebSocket connection state
func (*RecConn) ReadJSON ¶
ReadJSON reads the next JSON-encoded message from the connection and stores it in the value pointed to by v.
See the documentation for the encoding/json Unmarshal function for details about the conversion of JSON to a Go value.
If the connection is closed ErrNotConnected is returned
func (*RecConn) ReadMessage ¶
ReadMessage is a helper method for getting a reader using NextReader and reading from that reader to a buffer.
If the connection is closed ErrNotConnected is returned
func (*RecConn) SetTLSClientConfig ¶
func (*RecConn) Shutdown ¶
Shutdown gracefully closes the connection by sending the websocket.CloseMessage. The writeWait param defines the duration before the deadline of the write operation is hit.
type Server ¶
type Server struct {
*Options
// contains filtered or unexported fields
}
Server struct
type WebsocketClient ¶
type WebsocketClient struct {
// contains filtered or unexported fields
}
func (*WebsocketClient) Connect ¶
func (ws *WebsocketClient) Connect() error
func (*WebsocketClient) Run ¶
func (ws *WebsocketClient) Run() error
type WebsocketServer ¶
type WebsocketServer struct {
// contains filtered or unexported fields
}
func (*WebsocketServer) Close ¶
func (ws *WebsocketServer) Close()
func (*WebsocketServer) IsConnected ¶
func (ws *WebsocketServer) IsConnected() bool
func (*WebsocketServer) ReadMessage ¶
func (ws *WebsocketServer) ReadMessage() (messageType int, message []byte, err error)
func (*WebsocketServer) WriteMessage ¶
func (ws *WebsocketServer) WriteMessage(messageType int, data []byte) error
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
helloworld/client
command
|
|
|
helloworld/server
command
|
|
|
timeout/client
command
|
|
|
timeout/server
command
|
|