websocket

package
v0.0.0-...-40ef913 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2021 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Handler websocket.Handler = func(conn *websocket.Conn) {
	c := &Conn{
		C: conn,
	}

	m.Lock()
	c.ID = index
	connections[index] = c
	index++
	m.Unlock()

	OnConnect(c)

	var (
		data []byte
		err  error
	)
	for {
		err = websocket.Message.Receive(c.C, &data)
		if err != nil {

			OnError(c, err)
			break
		}

		OnMessage(c, data)
	}

	m.Lock()
	delete(connections, c.ID)
	m.Unlock()
}

Handler 最重要的入口

View Source
var OnConnect func(*Conn)

OnConnect 当客户端与服务端建立WebSocket连接时触发的回调函数,每个连接只会触发一次

View Source
var OnError func(*Conn, error)

OnError 当客户端的连接上发生错误时触发,特别注意:客户端断开连接也是触发本函数

View Source
var OnMessage func(*Conn, []byte)

OnMessage 当客户端通过连接发来数据时触发的回调函数

Functions

This section is empty.

Types

type Conn

type Conn struct {
	ID int // ID

	C *websocket.Conn // golang.org/x/net/websocket的Conn

	Data interface{} // 可以用来储存自定义数据,比如用户ID
}

Conn 表示WebSocket连接,协程安全

func Get

func Get(id int) (r *Conn)

Get 获取Conn

func GetAll

func GetAll() []*Conn

GetAll 获取所有Conn

func (*Conn) Send

func (c *Conn) Send(v interface{}) error

Send 可以发送string或[]byte

func (*Conn) SendJSON

func (c *Conn) SendJSON(v interface{}) error

SendJSON 发送JSON格式数据

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL