123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package msq
- import "errors"
- import "fmt"
- import "log"
- type Sender interface {
- Send(interface{}) error
- Close() error
- }
- //具体的发送策略让客户端来做
- type ChanServer struct {
- private map[int64]Sender
- public map[int64]Sender
- }
- func NewChanServer() *ChanServer {
- server := &ChanServer{}
- server.private = make(map[int64]Sender)
- server.public = make(map[int64]Sender)
- return server
- }
- func (server *ChanServer) Bind(ty int, id int64, sender Sender) {
- if ty == Private {
- server.private[id] = sender
- }
- if ty == Public {
- server.public[id] = sender
- }
- }
- func (server *ChanServer) UnBind(ty int, id int64) {
- if ty == Private {
- delete(server.private, id)
- }
- if ty == Public {
- delete(server.public, id)
- }
- }
- func (server *ChanServer) Send(ty int, id int64, data interface{}) error {
- if ty == Private {
- return server.sendOne(server.private, ty, id, data)
- } else {
- return server.sendOne(server.public, ty, id, data)
- }
- return nil
- }
- func (server *ChanServer) sendOne(senders map[int64]Sender, ty int, id int64, data interface{}) error {
- if id == 0 {
- for newid, v := range senders {
- err := v.Send(data)
- if err != nil {
- server.UnBind(ty, newid)
- v.Close()
- }
- }
- } else {
- if sender, ok := senders[id]; ok {
- err := sender.Send(data)
- if err != nil {
- server.UnBind(ty, id)
- sender.Close()
- }
- } else {
- err := errors.New("sendOne error, id not exist" + fmt.Sprint(id))
- log.Println(err)
- return err
- }
- }
- return nil
- }
- //默认向所有的public的客户端发送
- func (server *ChanServer) SendPublic(msg *Message) error {
- return server.Send(Public, 0, msg)
- }
- func (server *ChanServer) SendPrivate(msg *Message) error {
- return server.Send(Private, msg.ClientId, msg)
- }
|