99 lines
2.2 KiB
Go
99 lines
2.2 KiB
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"game/common/proto/pb"
|
|
"game/test/client/config"
|
|
"github.com/fox/fox/ipb"
|
|
"github.com/fox/fox/log"
|
|
"github.com/fox/fox/processor"
|
|
"github.com/fox/fox/service"
|
|
"github.com/fox/fox/ws"
|
|
"github.com/golang/protobuf/proto"
|
|
)
|
|
|
|
var Chat []*ClientService
|
|
|
|
type ClientService struct {
|
|
*service.BaseService
|
|
client *ws.Client
|
|
processor *processor.Processor
|
|
}
|
|
|
|
func Init() {
|
|
for i := 0; i < config.Command.ServiceNum; i++ {
|
|
sid := config.Command.ServiceId + i
|
|
if srv := newClientService(sid); srv != nil {
|
|
Chat = append(Chat, srv)
|
|
}
|
|
}
|
|
}
|
|
|
|
func Stop() {
|
|
for _, srv := range Chat {
|
|
srv.NotifyStop()
|
|
}
|
|
for _, srv := range Chat {
|
|
srv.WaitStop()
|
|
}
|
|
}
|
|
|
|
func newClientService(serviceId int) *ClientService {
|
|
var err error
|
|
s := new(ClientService)
|
|
|
|
sName := fmt.Sprintf("%v-%d", "client", serviceId)
|
|
s.BaseService = service.NewBaseService("client", sName, s, s)
|
|
size := len(config.Cfg.Special.Address)
|
|
addr := config.Cfg.Special.Address[serviceId%size]
|
|
if s.client, err = ws.NewClient(fmt.Sprintf("ws://%v", addr), s); err != nil {
|
|
return nil
|
|
}
|
|
s.processor = processor.NewProcessor()
|
|
s.initProcessor()
|
|
s.OnInit()
|
|
return s
|
|
}
|
|
|
|
func (s *ClientService) OnInit() {
|
|
s.client.Start()
|
|
s.BaseService.Run()
|
|
log.Debug("onInit")
|
|
}
|
|
|
|
func (s *ClientService) CanStop() bool {
|
|
return true
|
|
}
|
|
|
|
func (s *ClientService) OnStop() {
|
|
s.client.Stop()
|
|
log.Debug("OnStop")
|
|
}
|
|
|
|
// 处理其它服发送过来的消息
|
|
func (s *ClientService) OnMessage(data []byte) error {
|
|
var cMsg = &pb.ClientMsg{}
|
|
var err error
|
|
if err = proto.Unmarshal(data, cMsg); err != nil {
|
|
log.Error(err.Error())
|
|
return err
|
|
}
|
|
if req, err := s.processor.Unmarshal(cMsg.MsgId, cMsg.Data); err == nil {
|
|
err = s.processor.Dispatch(cMsg.MsgId, cMsg.UserId, cMsg, req)
|
|
}
|
|
//log.Debug(s.Log("on message:%v", string(cMsg)))
|
|
return nil
|
|
}
|
|
|
|
// 向内部服务发送消息
|
|
func (s *ClientService) SendServiceData(topic string, userId int64, msgId int32, data []byte) {
|
|
iMsg := ipb.MakeMsg(s.Name(), 0, userId, msgId, data)
|
|
_ = s.Send(topic, iMsg)
|
|
}
|
|
|
|
// 向内部服务发送消息
|
|
func (s *ClientService) SendServiceMsg(topic string, userId int64, msgId int32, msg proto.Message) {
|
|
data, _ := proto.Marshal(msg)
|
|
s.SendServiceData(topic, userId, msgId, data)
|
|
}
|