SignalR框架下实现golang的客户端和服务端

服务端:

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值