feat(ws): release generic WebSocket client and server v0.31.0-preview
This commit is contained in:
17
examples/websocket/README.md
Normal file
17
examples/websocket/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# WebSocket 通用示例
|
||||
|
||||
不依赖外部基础设施,默认在随机本机端口启动 GoOmni Server、Go Client 和 Hub,完成文本回显、分组广播后排空退出:
|
||||
|
||||
```sh
|
||||
go run ./examples/websocket
|
||||
```
|
||||
|
||||
预期输出 `hello websocket`、`hello group`。浏览器标准 WebSocket 示例:
|
||||
|
||||
```sh
|
||||
go run ./examples/websocket -serve
|
||||
```
|
||||
|
||||
打开 http://127.0.0.1:8088 的两个标签页,点击连接、发送、广播。Ctrl+C 触发 HTTP 排空、WS Stop/Drain、Hub 关闭。示例只监听 loopback,无鉴权;接入项目在升级前验证自己的身份和分组权限。浏览器使用同源策略;跨域部署通过明确的 `AllowedOrigins` 配置。
|
||||
|
||||
完整 API、限制与安全说明见 [ws](../../ws/README.md);双向调用与重连订阅见 [websocketRPC](../websocketRPC/README.md)。
|
||||
16
examples/websocket/index.html
Normal file
16
examples/websocket/index.html
Normal file
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>GoOmni WebSocket 示例</title>
|
||||
<style>body{font:16px system-ui;max-width:720px;margin:60px auto;padding:0 24px;color:#182b3d}button,input{font:inherit;padding:10px;margin:4px}pre{white-space:pre-wrap;background:#f2f5f8;padding:20px;min-height:180px}#state{color:#52697b}</style>
|
||||
<h1>WebSocket 回显与分组广播</h1><p>打开两个标签页,连接后发送文本或广播。</p>
|
||||
<p id="state">未连接</p><button id="connect">连接</button><button id="disconnect">断开</button>
|
||||
<p><input id="message" value="你好 WebSocket" aria-label="消息"><button id="send">发送</button><button id="broadcast">广播</button></p><pre id="log"></pre>
|
||||
<script>
|
||||
let socket; const log=document.querySelector('#log'),state=document.querySelector('#state');
|
||||
function append(text){log.textContent=(log.textContent+text+'\n').slice(-12000)}
|
||||
document.querySelector('#connect').onclick=()=>{if(socket&&socket.readyState<2)return;socket=new WebSocket((location.protocol==='https:'?'wss://':'ws://')+location.host+'/ws');socket.onopen=()=>state.textContent='已连接';socket.onmessage=e=>append('收到:'+e.data);socket.onclose=e=>state.textContent='已断开,关闭码 '+e.code;socket.onerror=()=>append('连接发生错误')};
|
||||
function send(value){if(socket?.readyState===WebSocket.OPEN){socket.send(value);append('发送:'+value)}else append('请先连接')}
|
||||
document.querySelector('#send').onclick=()=>send(document.querySelector('#message').value);
|
||||
document.querySelector('#broadcast').onclick=()=>send('broadcast');
|
||||
document.querySelector('#disconnect').onclick=()=>socket?.close(1000,'');
|
||||
</script></html>
|
||||
107
examples/websocket/main.go
Normal file
107
examples/websocket/main.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
omni "git.yuntuo.hk/k2safe/go-omni"
|
||||
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
||||
"git.yuntuo.hk/k2safe/go-omni/ws"
|
||||
"git.yuntuo.hk/k2safe/go-omni/ws/hub"
|
||||
wsomni "git.yuntuo.hk/k2safe/go-omni/ws/omni"
|
||||
)
|
||||
|
||||
//go:embed index.html
|
||||
var page []byte
|
||||
|
||||
func main() {
|
||||
serve := flag.Bool("serve", false, "serve the browser demo on 127.0.0.1:8088")
|
||||
flag.Parse()
|
||||
if err := run(*serve); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(serve bool) (runErr error) {
|
||||
application := omni.New(omni.WithLogger(false))
|
||||
defer func() { runErr = errors.Join(runErr, application.Close()) }()
|
||||
connections, err := hub.New(hub.Config{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
application.OnShutdown(connections.Close)
|
||||
server, err := ws.NewServer(ws.ServerConfig{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = wsomni.Mount(application, "/ws", server, ws.Handlers{
|
||||
OnOpen: func(_ context.Context, s *ws.Session) error {
|
||||
if err := connections.Add(s); err != nil {
|
||||
return err
|
||||
}
|
||||
return connections.Join(s.ID(), "demo")
|
||||
},
|
||||
OnMessage: func(ctx context.Context, s *ws.Session, m ws.Message) error {
|
||||
if m.Type == ws.Text && string(m.Data) == "broadcast" {
|
||||
result, err := connections.SendGroup("demo", ws.Message{Type: ws.Text, Data: []byte("hello group")})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(result.Errors) > 0 {
|
||||
return s.SendJSON(ctx, map[string]int{"queued": result.Queued, "failed": len(result.Errors)})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return s.Send(ctx, m)
|
||||
},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
application.GET("/", func(c *httpx.Context) error {
|
||||
c.Raw().Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, err := c.Raw().Write(page)
|
||||
return err
|
||||
})
|
||||
if serve {
|
||||
fmt.Println("Open http://127.0.0.1:8088 in two browser tabs; Ctrl+C stops cleanly.")
|
||||
return application.Run("127.0.0.1:8088")
|
||||
}
|
||||
httpServer := httptest.NewServer(application)
|
||||
defer httpServer.Close()
|
||||
client, err := ws.NewClient(ws.ClientConfig{ProxyMode: "direct"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
runErr = errors.Join(runErr, client.Shutdown(ctx))
|
||||
}()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
replies := make(chan string, 2)
|
||||
session, err := client.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/ws", ws.Handlers{OnMessage: func(_ context.Context, _ *ws.Session, m ws.Message) error { replies <- string(m.Data); return nil }})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, message := range []string{"hello websocket", "broadcast"} {
|
||||
if err = session.Send(ctx, ws.Message{Type: ws.Text, Data: []byte(message)}); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case reply := <-replies:
|
||||
fmt.Println(reply)
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user