Documentation
¶
Index ¶
- Constants
- Variables
- type BufferPoolKey
- type CheckOriginKey
- type Connection
- type ConnectionFunc
- type ConnectionValues
- type DisconnectFunc
- type Emitter
- type ErrorFunc
- type ErrorKey
- type LeaveRoomFunc
- type MessageFunc
- type NativeMessageFunc
- type Option
- func WithCheckOrigin(checkOrigin func(r *http.Request) bool) Option
- func WithEnableCompression(enableCompression bool) Option
- func WithError(err func(w http.ResponseWriter, r *http.Request, status int, reason error)) Option
- func WithHandshakeTimeout(handshakeTimeout time.Duration) Option
- func WithReadBufferSize(readBuffSize int) Option
- func WithSubprotocols(subProtocols []string) Option
- func WithWriteBufferPool(writeBufferPool websocket.BufferPool) Option
- func WithWriteBufferSize(writeBuffSize int) Option
- type Options
- type PingFunc
- type PongFunc
- type Server
- func (s *Server) Disconnect(connID string) (err error)
- func (s *Server) GetConnection(connID string) Connection
- func (s *Server) GetConnections() []Connection
- func (s *Server) GetConnectionsByRoom(roomName string) []Connection
- func (s *Server) GetTotalConnections() (n int)
- func (s *Server) Handler() func(ctx *gin.Context)
- func (s *Server) IsConnected(connID string) bool
- func (s *Server) IsJoined(roomName string, connID string) bool
- func (s *Server) Join(roomName string, connID string)
- func (s *Server) Leave(roomName string, connID string) bool
- func (s *Server) LeaveAll(connID string)
- func (s *Server) OnConnection(cb ConnectionFunc)
- func (s *Server) Upgrade(ctx *gin.Context) Connection
- type UnderlineConnection
- type Websocket
Constants ¶
const ( // All is the string which the Emitter use to send a message to all. All = "" // Broadcast is the string which the Emitter use to send a message to all except this connection. Broadcast = ";to;all;except;me;" )
const CloseMessage = websocket.CloseMessage
CloseMessage denotes a close control message. The optional message payload contains a numeric code and text. Use the FormatCloseMessage function to format a close message payload.
Use the `Connection#Disconnect` instead.
const ( // WriteWait is 1 second at the internal implementation, // same as here but this can be changed at the future* WriteWait = 1 * time.Second )
Variables ¶
var ClientSource []byte
var ErrAlreadyDisconnected = errors.New("already disconnected")
ErrAlreadyDisconnected can be reported on the `Connection#Disconnect` function whenever the caller tries to close the connection when it is already closed by the client or the caller previously.
Functions ¶
This section is empty.
Types ¶
type BufferPoolKey ¶
type BufferPoolKey struct{}
type CheckOriginKey ¶
type CheckOriginKey struct{}
type Connection ¶
type Connection interface {
// Emitter implements EmitMessage & Emit
Emitter
// Err is not nil if the upgrader failed to upgrade http to websocket connection.
Err() error
// ID returns the connection's identifier
ID() string
// Server returns the websocket server instance
// which this connection is listening to.
//
// Its connection-relative operations are safe for use.
Server() *Server
// Write writes a raw websocket message with a specific type to the client
// used by ping messages and any CloseMessage types.
Write(websocketMessageType int, data []byte) error
// Context returns the (upgraded) context.Context of this connection
// avoid using it, you normally don't need it,
// websocket has everything you need to authenticate the user BUT if it's necessary
// then you use it to receive user information, for example: from headers
Context() *gin.Context
// OnDisconnect registers a callback which is fired when this connection is closed by an error or manual
OnDisconnect(DisconnectFunc)
// OnError registers a callback which fires when this connection occurs an error
OnError(ErrorFunc)
// OnPing registers a callback which fires on each ping
OnPing(PingFunc)
// OnPong registers a callback which fires on pong message received
OnPong(PongFunc)
// FireOnError can be used to send a custom error message to the connection
//
// It does nothing more than firing the OnError listeners. It doesn't send anything to the client.
FireOnError(err error)
// To defines on what "room" (see Join) the server should send a message
// returns an Emmiter(`EmitMessage` & `Emit`) to send messages.
To(string) Emitter
// OnMessage registers a callback which fires when native websocket message received
OnMessage(NativeMessageFunc)
// On registers a callback to a particular event which is fired when a message to this event is received
On(string, MessageFunc)
// Join registers this connection to a room, if it doesn't exist then it creates a new. One room can have one or more connections. One connection can be joined to many rooms. All connections are joined to a room specified by their `ID` automatically.
Join(string)
// IsJoined returns true when this connection is joined to the room, otherwise false.
// It Takes the room name as its input parameter.
IsJoined(roomName string) bool
// Leave removes this connection entry from a room
// Returns true if the connection has actually left from the particular room.
Leave(string) bool
// OnLeave registers a callback which fires when this connection left from any joined room.
// This callback is called automatically on Disconnected client, because websocket server automatically
// deletes the disconnected connection from any joined rooms.
//
// Note: the callback(s) called right before the server deletes the connection from the room
// so the connection theoretical can still send messages to its room right before it is being disconnected.
OnLeave(roomLeaveCb LeaveRoomFunc)
// Wait starts the pinger and the messages reader,
// it's named as "Wait" because it should be called LAST,
// after the "On" events IF server's `Upgrade` is used,
// otherise you don't have to call it because the `Handler()` does it automatically.
Wait()
// Disconnect disconnects the client, close the underline websocket conn and removes it from the conn list
// returns the error, if any, from the underline connection
Disconnect() error
// SetValue sets a key-value pair on the connection's mem store.
SetValue(key string, value interface{})
// GetValue gets a value by its key from the connection's mem store.
GetValue(key string) interface{}
// GetValueArrString gets a value as []string by its key from the connection's mem store.
GetValueArrString(key string) []string
// GetValueString gets a value as string by its key from the connection's mem store.
GetValueString(key string) string
// GetValueInt gets a value as integer by its key from the connection's mem store.
GetValueInt(key string) int
}
Connection is the front-end API that you will use to communicate with the client side
type ConnectionFunc ¶ added in v1.2.1
type ConnectionFunc func(Connection)
ConnectionFunc is the callback which fires when a client/connection is connected to the Server. Receives one parameter which is the Connection
type ConnectionValues ¶ added in v1.2.1
type ConnectionValues []connectionValue
func (*ConnectionValues) Get ¶ added in v1.2.1
func (r *ConnectionValues) Get(key string) interface{}
func (*ConnectionValues) Reset ¶ added in v1.2.1
func (r *ConnectionValues) Reset()
func (*ConnectionValues) Set ¶ added in v1.2.1
func (r *ConnectionValues) Set(key string, value interface{})
type DisconnectFunc ¶ added in v1.2.1
type DisconnectFunc func()
DisconnectFunc is the callback which is fired when a client/connection closed
type Emitter ¶ added in v1.2.1
type Emitter interface {
// EmitMessage sends a native websocket message
EmitMessage([]byte) error
// Emit sends a message on a particular event
Emit(string, interface{}) error
}
Emitter is the message/or/event manager
type ErrorFunc ¶ added in v1.2.1
type ErrorFunc (func(error))
ErrorFunc is the callback which fires whenever an error occurs
type LeaveRoomFunc ¶ added in v1.2.1
type LeaveRoomFunc func(roomName string)
LeaveRoomFunc is the callback which is fired when a client/connection leaves from any room. This is called automatically when client/connection disconnected (because websocket server automatically leaves from all joined rooms)
type MessageFunc ¶ added in v1.2.1
type MessageFunc interface{}
MessageFunc is the second argument to the Emitter's Emit functions. A callback which should receives one parameter of type string, int, bool or any valid JSON/Go struct
type NativeMessageFunc ¶ added in v1.2.1
type NativeMessageFunc func([]byte)
NativeMessageFunc is the callback for native websocket messages, receives one []byte parameter which is the raw client's message
type Option ¶
type Option func(*Options)
func WithEnableCompression ¶
func WithHandshakeTimeout ¶
func WithReadBufferSize ¶
func WithSubprotocols ¶
func WithWriteBufferPool ¶
func WithWriteBufferPool(writeBufferPool websocket.BufferPool) Option
func WithWriteBufferSize ¶
type PongFunc ¶ added in v1.2.1
type PongFunc func()
PongFunc is the callback which fires on pong message received
type Server ¶ added in v1.2.1
type Server struct {
ClientSource []byte
// contains filtered or unexported fields
}
Server is the websocket Server's implementation.
It listens for websocket clients (either from the javascript client-side or from any websocket implementation). See `OnConnection` , to register a single event which will handle all incoming connections and the `Handler` which builds the upgrader handler that you can register to a route based on an Endpoint.
To serve the built'n javascript client-side library look the `websocket.ClientHandler`.
func (*Server) Disconnect ¶ added in v1.2.1
Disconnect force-disconnects a websocket connection based on its connection.ID() What it does? 1. remove the connection from the list 2. leave from all joined rooms 3. fire the disconnect callbacks, if any 4. close the underline connection and return its error, if any.
You can use the connection.Disconnect() instead.
func (*Server) GetConnection ¶ added in v1.2.1
func (s *Server) GetConnection(connID string) Connection
GetConnection returns single connection
func (*Server) GetConnections ¶ added in v1.2.1
func (s *Server) GetConnections() []Connection
GetConnections returns all connections
func (*Server) GetConnectionsByRoom ¶ added in v1.2.1
func (s *Server) GetConnectionsByRoom(roomName string) []Connection
GetConnectionsByRoom returns a list of Connection which are joined to this room.
func (*Server) GetTotalConnections ¶ added in v1.2.1
GetTotalConnections returns the number of total connections
func (*Server) Handler ¶ added in v1.2.1
Handler builds the handler based on the configuration and returns it. It should be called once per Server, its result should be passed as a middleware to an iris route which will be responsible to register the websocket's endpoint.
Endpoint is the path which the websocket Server will listen for clients/connections.
To serve the built'n javascript client-side library look the `websocket.ClientHandler`.
func (*Server) IsConnected ¶ added in v1.2.1
IsConnected returns true if the connection with that ID is connected to the Server useful when you have defined a custom connection id generator (based on a database) and you want to check if that connection is already connected (on multiple tabs)
func (*Server) IsJoined ¶ added in v1.2.1
IsJoined reports if a specific room has a specific connection into its values. First parameter is the room name, second is the connection's id.
It returns true when the "connID" is joined to the "roomName".
func (*Server) Join ¶ added in v1.2.1
Join joins a websocket client to a room, first parameter is the room name and the second the connection.ID()
You can use connection.Join("room name") instead.
func (*Server) Leave ¶ added in v1.2.1
Leave leaves a websocket client from a room, first parameter is the room name and the second the connection.ID()
You can use connection.Leave("room name") instead. Returns true if the connection has actually left from the particular room.
func (*Server) LeaveAll ¶ added in v1.2.1
LeaveAll kicks out a connection from ALL of its joined rooms
func (*Server) OnConnection ¶ added in v1.2.1
func (s *Server) OnConnection(cb ConnectionFunc)
OnConnection is the main event you, as developer, will work with each of the websocket connections.
func (*Server) Upgrade ¶ added in v1.2.1
func (s *Server) Upgrade(ctx *gin.Context) Connection
Upgrade upgrades the HTTP Server connection to the WebSocket protocol.
The responseHeader is included in the response to the client's upgrade request. Use the responseHeader to specify cookies (Set-Cookie) and the application negotiated subprotocol (Sec--Protocol).
If the upgrade fails, then Upgrade replies to the client with an HTTP error response and the return `Connection.Err()` is filled with that error.
For a more high-level function use the `Handler()` and `OnConnecton` events. This one does not starts the connection's writer and reader, so after your `On/OnMessage` events registration the caller has to call the `Connection#Wait` function, otherwise the connection will be not handled.
type UnderlineConnection ¶ added in v1.2.1
type UnderlineConnection interface {
// SetWriteDeadline 设置底层连接写入超时时限, 如果写入超时. websocket 连接状态变为已损坏,
// 之后所有的写入操作都会返回错误, t 如果为零值则写入不会超时
SetWriteDeadline(t time.Time) error
// SetReadDeadline 设置底层连接读取超时时限, 如果读取超时, websocket 连接状态变为已损坏,
// 之后所有的读取都会返回错误, t 为零值表明写入不会超时
SetReadDeadline(t time.Time) error
// SetReadLimit 设置连接从对等方读取数据的最大大小, 如果超出该值, 则连接将向对等方发送关闭帧并返回 ErrReadLimit 错误
SetReadLimit(limit int64)
// SetPongHandler 设置从对等方接收到的 pong 消息的处理函数. h 的 appData 参数是 PONG 框架应用程序数据.
// 默认的 pong 处理函数什么都不做.
SetPongHandler(h func(appData string) error)
// SetPingHandler 设置从对等方接收到的 ping 消息的处理程序。 h 的 appData 参数是 PING 帧应用程序数据。
// 默认的 ping 处理程序向对等方发送一个 pong。
SetPingHandler(h func(appData string) error)
// WriteControl 在给定的期限内写入一条控制消息。允许的消息类型是 CloseMessage、PingMessage 和 PongMessage。
WriteControl(messageType int, data []byte, deadline time.Time) error
// WriteMessage 是一个辅助方法,用于使用 NextWriter 获取写入器,写入消息并关闭写入器。
WriteMessage(messageType int, data []byte) error
// ReadMessage 是一种帮助方法,用于使用 NextReader 获取阅读器并从该阅读器读取到缓冲区。
ReadMessage() (messageType int, p []byte, err error)
// NextWriter 为下一条要发送的消息返回一个 writer。 writer 的 Close 方法将完整的消息刷新到网络。
// 一个连接上最多可以有一个打开的写入器。如果应用程序尚未关闭前一个写入器,NextWriter 将关闭它。
NextWriter(messageType int) (io.WriteCloser, error)
// Close 关闭底层网络连接而不发送或等待关闭帧。
Close() error
}
type Websocket ¶
func New ¶
New returns a new websocket Server based on a configuration. See `OnConnection` , to register a single event which will handle all incoming connections and the `Handler` which builds the upgrader handler that you can register to a route based on an Endpoint.
To serve the built'n javascript client-side library look the `websocket.ClientHandler`.