sse

package
v0.0.0-...-e53d801 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2024 License: MIT Imports: 10 Imported by: 0

README

Server-Sent Events (SSE)

快速开始

Server 使用手册
核心结构体
// Packet server 消息包
type Packet struct {
   Message   Message `json:"message"` //发送内容消息体
   Zone      string  //类似区域概念,每个连接可以在不同区域中
   ID        string  `json:"id"` //连接ID,用于标识连接
   Broadcast bool    //是否广播
}

// Message sse消息内容
type Message struct {
	Event string //server 监听事件名称,必填
	Data  string //发送内容
}
消息推送

SendMessage() 方法发送消息 Packet不同参数有不同逻辑 如下:

  • Zone == "" && Broadcast == true && ID== "" , 全域广播(所有连接全部发送消息)

  • Zone != "" && Broadcast == true && ID== "" , Zone正确 并且 存在连接时进行 域内广播(同意区域内全部发送消息)

  • Zone != "" && ID != "" , 找到指定ID连接 进行消息发送

  1. 引入包,初始化一个hub
import "github.com/EilenC/ecommon/sse"
var h = sse.NewHub(nil)
  1. 在http监听中,转给hub中的 RegisterBlock() 方法处理
http.HandleFunc("/server", sse)
sse := func(w http.ResponseWriter, r *http.Request) {
    h.RegisterBlock(w, r, "zone ID 可以选值 为空默认为default", nil)
}
  1. 发送消息,使用hub中的 SendMessage() 方法发送
http.HandleFunc("/send", send)
send := func(w http.ResponseWriter, r *http.Request) {
	user := r.FormValue("user")
	content := r.FormValue("content")
	msg := make(map[string]interface{})
	msg["msg"] = content
	msg["time"] = time.Now().UnixMilli()
	b, _ := json.Marshal(msg)
	err := h.SendMessage(sse.Packet{
		Message: &sse.Message{
			Event: "customEvent",
			Data:  string(b),
		},
		Zone:      "default",
		ClientID:  user,
		Broadcast: user == "",
	})
	if err != nil {
		fmt.Printf("send message fail %+v\n", err)
		_, _ = w.Write([]byte(err.Error()))
		return
	}
}
Client 使用手册
连接服务

[NewClient()] 根据参数初始化一个Client

参数:

  1. Server-sent Event 服务地址
  2. 请求方法 (default:GET)
  3. 断开连接后重连时间
client := sse.NewClient("http://localhost:8080/sse", http.MethodGet, 3*time.Second)
client.Start()
监听事件
// 自定义事件处理逻辑
client.OnEvent("customEvent", func(event *sse.Message) {
    fmt.Printf("ID:%s 收到 %s 事件: %s\n", event.ID, event.Event, event.Data)
})
连接成功与断开回调
// 连接建立时的处理逻辑
client.OnConnection(func() {
    fmt.Println("连接已建立")
})

// 连接错误时的处理逻辑
client.OnError(func(err error) {
    fmt.Println("连接错误:", err)
})

示例

Server:

具体代码请参考example/server.go

  1. 初始化SSE连接

    index

  2. 发送消息

    send

Client:

具体代码请参考example/client.go

客户端与Web端通信

client

Documentation

Overview

Package sse implements Server-Sent Events, as specified in RFC 6202.

Index

Constants

View Source
const (
	EOF = "\n"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(url, method string, reconnectDelay time.Duration) *Client

func (*Client) OnConnection

func (c *Client) OnConnection(handler func())

OnConnection callback function upon successful connection registration (not guaranteed to be faster than the first response data)

func (*Client) OnDisconnect

func (c *Client) OnDisconnect(handler func(err string))

OnDisconnect callback function when connection is disconnected

func (*Client) OnExit

func (c *Client) OnExit(handler func())

OnExit callback function when client stop

func (*Client) Start

func (c *Client) Start()

func (*Client) Stop

func (c *Client) Stop()

Stop client stop connect

func (*Client) SubscribeEvent

func (c *Client) SubscribeEvent(eventName string, callback EventCallback)

SubscribeEvent Subscribe to callbacks for events

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder sse 解码器

func NewDecoder

func NewDecoder(reader io.Reader) *Decoder

NewDecoder sever-sent events

func (*Decoder) Decode

func (d *Decoder) Decode() (*Message, error)

Decode sever-sent events message decode

type EventCallback

type EventCallback func(message *Message)

EventCallback Define the type of SSE event subscription callback function

type Hub

type Hub struct {
	ConnectedFunc  func(clientID string) //连接建立时的处理逻辑
	DisconnectFunc func(clientID string) //连接建立时的处理逻辑
	// contains filtered or unexported fields
}

Hub Global SSE Hub reply is nil, no record push message, otherwise it will record

func NewHub

func NewHub(log Log) *Hub

NewHub returns SSE total hub designed to return push data for easy logging

func (*Hub) RegisterBlock

func (hub *Hub) RegisterBlock(w http.ResponseWriter, r *http.Request, zone string, uuid func() string)

RegisterBlock registers SSE connections Zone string zone names default Uuid func() string is a function that generates a connection ID, using GetClientID() by default

func (*Hub) SendMessage

func (hub *Hub) SendMessage(pkg Packet) error

SendMessage sends messages, whether to broadcast is controlled by the Packet parameter

func (*Hub) StartBroadcast

func (hub *Hub) StartBroadcast()

StartBroadcast messages to all connections

func (*Hub) UnRegisterBlock

func (hub *Hub) UnRegisterBlock(zone, id string)

UnRegisterBlock Unregister Connection Delete Data in Map

type Link struct {
	// contains filtered or unexported fields
}

Link server 连接 messageChan 推送消息通道 createTime 连接创建时的时间戳(秒级)

type Log

type Log interface {
	Info(args ...interface{})
	Infoln(args ...interface{})
	Infof(format string, args ...interface{})

	Debug(args ...interface{})
	Debugln(args ...interface{})
	Debugf(format string, args ...interface{})

	Warn(args ...interface{})
	Warnln(args ...interface{})
	Warnf(format string, args ...interface{})

	Error(args ...interface{})
	Errorln(args ...interface{})
	Errorf(format string, args ...interface{})
}

Log 常用日志结构体注入接口

type Message

type Message struct {
	ID      string //消息ID,可选
	Event   string //server 监听事件名称,必填
	Data    string //发送内容
	Retry   string //重试
	Comment string //注释
	// contains filtered or unexported fields
}

Message 消息内容

func (*Message) Format

func (m *Message) Format() (*strings.Builder, error)

Format format sse message

func (*Message) WriteConnect

func (m *Message) WriteConnect(w http.ResponseWriter) error

WriteConnect // Push message to client

type Packet

type Packet struct {
	Message   *Message `json:"message"` //发送内容消息体
	Zone      string   //类似区域概念,每个连接可以在不同区域中
	ClientID  string   `json:"client_id"` //连接ID,用于标识连接
	Broadcast bool     //是否广播
}

Packet server 消息包

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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