服务端:
import (
"context"
"fmt"
"log"
"net/http"
"time"
"github.com/philippseith/signalr"
)
type AppHub struct {
signalr.Hub
}
type Logger struct{}
func (l Logger) Log(keyVals ...interface{}) error {
//log.Println(keyVals...)
return nil
}
func (h *AppHub) OnConnected(connectionID string) {
log.Println(connectionID, " connected")
}
func (h *AppHub) OnDisconnected(connectionID string) {
log.Println(connectionID, " disconnected")
}
func (h *AppHub) ReceiveMessage(message string) {
//h.Clients().All().Send("SendMessage", time.Now().Format("2006/01/02 15:04:05"))
log.Println("ReceiveMessage", message)
}
func (h *AppHub) SendMessage(message string) {
log.Println("SendMessage", message)
h.Clients().All().Send("ReceiveMessage", message)
}
func main() {
server, _ := signalr.NewServer(
context.TODO(),
signalr.SimpleHubFactory(&AppHub{}),
signalr.KeepAliveInterval(2*time.Second),
signalr.Logger(Logger{}, true),
)
address := "localhost:8003"
// create a new http.ServerMux to handle your app's http requests
router := http.NewServeMux()
server.MapHTTP(signalr.WithHTTPServeMux(router), "/chatHub")
fmt.Printf("Listening for websocket connections on http://%s\n", address)
if err := http.ListenAndServe(address, router); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
客户端:
import (
"context"
"fmt"
"log"
"time"
"github.com/philippseith/signalr"
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
type MyReceiver struct {
signalr.Receiver
}
func (r *MyReceiver) ReceiveMessage(msg string) {
log.Println("ReceiveMessage:", msg)
if msg == "exit" {
r.Server().Send("abort")
}
}
type Logger struct{}
func (l Logger) Log(keyVals ...interface{}) error {
//log.Println(keyVals...)
return nil
}
func main() {
ctx := context.Background()
address := "http://localhost:8003/chatHub"
// 创建客户端
c, err := signalr.NewClient(context.Background(), nil,
signalr.WithReceiver(&MyReceiver{}),
//func()里面的东西可以自动重连机制,如果移出来就只会注册一次
signalr.WithConnector(func() (signalr.Connection, error) {
creationCtx, _ := context.WithTimeout(ctx, 2*time.Second)
return signalr.NewHTTPConnection(creationCtx, address)
}),
//signalr.Logger(nil, false),
signalr.Logger(Logger{}, false),
)
if err != nil {
panic(err)
}
c.Start()
fmt.Println("Client started")
var inText string
for {
fmt.Print("请输入文本: ")
_, _ = fmt.Scanln(&inText)
err := <-c.Send("SendMessage", inText)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}
}
附上signalr的版本信息:
github.com/philippseith/signalr v0.6.2