一起学go语言啦

[复制链接]
5228|42
 楼主| keer_zu 发表于 2016-11-30 10:45 | 显示全部楼层 |阅读模式
本帖最后由 keer_zu 于 2016-11-30 11:03 编辑

最近一个项目,需要go语言。
需要一个通信框架,可以并发处理多路链接和消息处理。

@21ic小喇叭 @yyy71cj @dong_abc

学go语言啦

学习 Go 语言(Golang).pdf (1.11 MB, 下载次数: 98)
 楼主| keer_zu 发表于 2016-11-30 10:47 | 显示全部楼层
go语言开发速度快,容易学,支持并发
垃圾回收
编译型语言,效率高
语法有脚本语言的特点
适合做服务器开发

就选go语言啦
........
 楼主| keer_zu 发表于 2016-11-30 10:55 | 显示全部楼层
首先在linux下安装go和sublime,其他组合也行,怎么习惯怎么来。网上大堆

如下图:
无标题.png
bei 011.jpg
 楼主| keer_zu 发表于 2016-11-30 10:59 | 显示全部楼层
随便给一个demo,顺便了解一下go的interface概念和struct概念。
当然,所有环境可以很容易在windows环境下搭建。

代码:
  1. package main

  2. import (
  3.         "fmt"
  4.         "message"
  5.         "time"
  6. )

  7. type S struct{ i int }

  8. func (p *S) Get() int  { return p.i }
  9. func (p *S) Put(v int) { p.i = v }

  10. type R struct{ i int }

  11. func (p *R) Get() int  { return p.i }
  12. func (p *R) Put(v int) { p.i = v }

  13. type I interface {
  14.         Get() int
  15.         Put(int)
  16. }

  17. func f(p I) {
  18.         fmt.Println(p.Get())
  19.         p.Put(1)
  20. }

  21. func f1(p I) {
  22.         switch p.(type) {

  23.         case *S:
  24.                 fmt.Println("---- *S")
  25.                 break
  26.         case *R:
  27.                 fmt.Println("---- *R")
  28.                 break
  29.         default:
  30.                 fmt.Println("---- no thing")
  31.                 break
  32.         }
  33. }

  34. var c chan int

  35. func ready(w string, sec int) {
  36.         time.Sleep(time.Duration(sec) * time.Second)
  37.         fmt.Println(w, "is ready!")
  38.         c <- 1
  39. }
  40. func main() {
  41.         da := message.DmcMessageAnalyzer{}
  42.         da.OnNewFrame(nil, nil)
  43.         var s S
  44.         var r R
  45.         s.i = 5
  46.         r.i = 6
  47.         f(&r)
  48.         f(&s)
  49.         f1(&r)
  50.         f1(&s)
  51.         c = make(chan int)
  52.         go ready("Tea", 2)
  53.         go ready("Coffee", 1)
  54.         fmt.Println("I'm waiting, but not too long...")
  55.         //time.Sleep(5 * time.Second)
  56.         f1 := <-c
  57.         fmt.Println("recv f1: ", f1)
  58.         f2 := <-c
  59.         fmt.Println("recv f2: ", f2)
  60.         fmt.Println("bye")
  61. }



 楼主| keer_zu 发表于 2016-11-30 11:01 | 显示全部楼层
上面代码被命名为:xxx.go
这里就叫test.go吧

然后使用go命令:
go build test.go

如果有错会提示,没有错误会得到可执行文件:test(windows下为test.exe)

就这么简单,玩起来吧。
 楼主| keer_zu 发表于 2016-11-30 11:18 | 显示全部楼层
然后可以尝试一个go的“大”项目
首先确保你的环境已经安装好git,
然后使用 go get github.com/xxx 命令得到该项目源代码

比如我要用到一个go的通信库,
go get github.com/pojoin/golis

执行完毕后,在你的go目录下回有这个project的代码,我的在:
/root/go/src/github.com/pojoin/golis 下面。

用到这个库的地方,import进来(比如下面代码):

  1. package main

  2. import (
  3.         "data_manager"
  4.         "fmt"
  5.         "github.com/pojoin/golis"
  6.         "message"
  7.         //        "time"
  8. )

  9. func main() {
  10.         s := golis.NewServer()
  11.         s.FilterChain().AddLast("test", &filter{})
  12.         s.SetCodecer(&echoProtocalCodec{})
  13.         s.RunOnPort("tcp", ":9090")
  14. }

  15. type echoProtocalCodec struct {
  16.         golis.ProtocalCodec
  17. }

  18. type dmc struct {
  19.         data_manager.DmcInfo
  20. }

  21. type stream struct {
  22.         data_manager.StreamInfo
  23. }

  24. type room struct {
  25.         data_manager.RoomInfo
  26. }

  27. type command struct {
  28.         message.Command
  29. }

  30. func (*echoProtocalCodec) Decode(buffer *golis.Buffer, dataCh chan<- interface{}) error {
  31.         //var i int

  32.         //length := buffer.GetWritePos()
  33.         fmt.Println("......Decode... len:", buffer.GetWritePos()-buffer.GetReadPos())
  34.         if buffer.GetWritePos()-buffer.GetReadPos() > 60 {
  35.                 fmt.Println("#################\n#######################\n#################\n#############\n")
  36.         }
  37.         /*
  38.                 for i = 0; i < length; i = i + 1 {
  39.                         fmt.Println(" ", buffer.GetBufItem(i))
  40.                         if buffer.GetBufItem(i) == 0x00 {
  41.                                 bs, _ := buffer.ReadBytes(i)
  42.                                 buffer.ResetRead()
  43.                                 buffer.ResetWrite()
  44.                                 if i < length-1 {
  45.                                         buffer.GetSlice(i+1, length-1)
  46.                                         dataCh <- bs
  47.                                         length = buffer.GetWritePos()
  48.                                         i = 0
  49.                                         continue
  50.                                 } else {
  51.                                         dataCh <- bs
  52.                                         break
  53.                                 }
  54.                         }
  55.                 }*/
  56.         bs, _ := buffer.ReadBytes(buffer.GetWritePos() - buffer.GetReadPos())
  57.         buffer.ResetRead()
  58.         buffer.ResetWrite()
  59.         dataCh <- bs

  60.         return nil
  61. }

  62. type filter struct{}

  63. func (*filter) SessionOpened(session *golis.Iosession) bool {
  64.         fmt.Println("session opened,the client is ", session.Conn().RemoteAddr().String())
  65.         fmt.Println("+ session id: ", session.Id())
  66.         return true
  67. }

  68. func (*filter) SessionClosed(session *golis.Iosession) bool {
  69.         fmt.Println("+ session closed, session id: ", session.Id())
  70.         return true
  71. }

  72. func (*filter) MsgReceived(session *golis.Iosession, msg interface{}) bool {
  73.         ma := message.DmcMessageAnalyzer{}
  74.         if bs, ok := msg.([]byte); ok {
  75.                 fmt.Println(".....MsgReceived....")
  76.                 ma.OnNewFrame(session, "+++ new frame!!!")
  77.                 fmt.Println("+ received msg :", string(bs))
  78.                 fmt.Println("+ session id: ", session.Id())
  79.                 //if session.Id()%3 == 1 {
  80.                 //        fmt.Println("start sleeping...")
  81.                 //        time.Sleep(3 * time.Second)
  82.                 //        fmt.Println("end sleep.")
  83.                 //}
  84.                 //replayMsg := fmt.Sprintf("echoServer received msg : %v", string(bs))
  85.                 ma.OnNewFrame(session, bs)
  86.                 //session.Write([]byte(replayMsg))
  87.         }
  88.         return true
  89. }

  90. func (*filter) MsgSend(session *golis.Iosession, message interface{}) bool {
  91.         fmt.Println("+ send msg, session id: ", session.Id())
  92.         return true
  93. }

  94. func (*filter) ErrorCaught(session *golis.Iosession, err error) bool {
  95.         fmt.Println("+ ErrorCaught, session id: %d", session.Id())
  96.         return true
  97. }


文件起名:golisTest.go

然后进入golisTest.go所在目录,执行:
    go build golisTest.go

编译器会自己在自己的/root/go/src目录下找到所依赖代码,最终生成可执行文件。
baiyunpiapia 发表于 2016-11-30 11:56 | 显示全部楼层
这种语言第一次听说哦
 楼主| keer_zu 发表于 2016-11-30 13:03 | 显示全部楼层
yyy71cj 发表于 2016-11-30 11:52
只要有用,语法倒是次要的
一看这风格,很好
多多分享 ...

编程风格是它自己调整的,你随便写,保存的一刹那就给你对齐了。
 楼主| keer_zu 发表于 2016-11-30 15:06 来自手机 | 显示全部楼层
baiyunpiapia 发表于 2016-11-30 11:56
这种语言第一次听说哦

google出品,今年编程语言排行榜上升最快语言
ddllxxrr 发表于 2016-11-30 18:22 | 显示全部楼层
go语言第一次听说,学习了

评论

现在go语言是不是很火了  发表于 2021-3-10 23:25
 楼主| keer_zu 发表于 2016-11-30 19:07 | 显示全部楼层
ddllxxrr 发表于 2016-11-30 18:22
go语言第一次听说,学习了

比较擅长并发和分布式环境。很多云平台的选择
 楼主| keer_zu 发表于 2016-11-30 20:10 | 显示全部楼层
命令部分:

  1. package message

  2. import (
  3.         //"fmt"
  4.         //"container/list"
  5.         "errors"
  6.         "github.com/pojoin/golis"
  7. )

  8. type CommandProperty int

  9. const (
  10.         ProvideResult CommandProperty = iota
  11.         NoProvideResult
  12. )

  13. type Command interface {
  14.         BuildResponse(info interface{}) (string, error)
  15.         CommandHandle(session *golis.Iosession) error
  16. }

  17. type CommandAttribute struct {
  18.         CommandName      string
  19.         MsgId            string
  20.         IsProvidedResult CommandProperty
  21. }

  22. type DmcCommandRegist struct {
  23.         cmdAtt    CommandAttribute
  24.         RoomId    int32
  25.         SessionId int32
  26. }

  27. func (dcr *DmcCommandRegist) BuildResponse(info interface{}) (string, error) {
  28.         return "abc", errors.New("cde")
  29. }

  30. func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession) error {
  31.         return errors.New("abc")
  32. }

  33. type CommandPool struct {
  34.         WaitMap map[string]*Command
  35. }

  36. func (cp *CommandPool) Add(cmd *Command, msgId string) {
  37.         cp.WaitMap[msgId] = cmd
  38. }

  39. type CommandDb struct {
  40.         CommandMap map[string]*Command
  41. }

  42. func (cdb *CommandDb) AddCommand(cmd *Command, cmdName string) {
  43.         cdb.CommandMap[cmdName] = cmd
  44. }

  45. func (cdb *CommandDb) GetCommand(name string) (*Command, error) {

  46.         if cdb.CommandMap[name] != nil {
  47.                 return cdb.CommandMap[name], nil
  48.         }

  49.         err := errors.New("This command is not exist! ")

  50.         return nil, err
  51. }
 楼主| keer_zu 发表于 2016-12-1 10:27 | 显示全部楼层
本帖最后由 keer_zu 于 2016-12-1 10:29 编辑

对上贴中的command和task概念做了区分,放在两个文件里面:
command.go和task.go

分别对CommandDb和TaskPool(上贴中CommandPool)实现了单例模式,保证对象实例的唯一性,使用测试函数做了测试,三个文件代码如下:

command.go:

  1. package message

  2. import (
  3.         "errors"
  4.         "fmt"
  5.         "github.com/pojoin/golis"
  6.         "sync"
  7. )

  8. var once sync.Once

  9. type CommandProperty int

  10. //const (
  11. //        ProvideResult CommandProperty = iota
  12. //        NoProvideResult
  13. //)

  14. type Command interface {
  15.         BuildResponse(info interface{}) (string, error)
  16.         CommandHandle(session *golis.Iosession) error
  17.         GetCommandName() string
  18.         IsProvidedResult() bool
  19. }

  20. type CommandAttribute struct {
  21.         CommandName string
  22.         //MsgId            string
  23.         IsProvidedResult bool //CommandProperty
  24. }

  25. type DmcCommandRegist struct {
  26.         cmdAtt    CommandAttribute
  27.         RoomId    int32
  28.         SessionId int32
  29. }

  30. func (dcr *DmcCommandRegist) BuildResponse(info interface{}) (string, error) {
  31.         return "abc", errors.New("cde")
  32. }

  33. func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession) error {
  34.         return errors.New("abc")
  35. }

  36. func (dcr *DmcCommandRegist) GetCommandName() string {
  37.         return dcr.cmdAtt.CommandName
  38. }

  39. func (dcr *DmcCommandRegist) IsProvidedResult() bool {
  40.         return dcr.cmdAtt.IsProvidedResult
  41. }

  42. type CommandDb struct {
  43.         CommandMap map[string]*Command
  44. }

  45. var commandDbInstance *CommandDb

  46. func GetCommandDbInstance() *CommandDb {
  47.         once.Do(func() {
  48.                 fmt.Println("+++++++++++ commandDb instance +++++++")
  49.                 commandDbInstance = &CommandDb{}
  50.         })
  51.         return commandDbInstance
  52. }

  53. func (cdb *CommandDb) AddCommand(cmd *Command, cmdName string) {
  54.         cdb.CommandMap[cmdName] = cmd
  55. }

  56. func (cdb *CommandDb) GetCommand(name string) (*Command, error) {

  57.         if cdb.CommandMap[name] != nil {
  58.                 return cdb.CommandMap[name], nil
  59.         }

  60.         err := errors.New("This command is not exist!")

  61.         return nil, err
  62. }




task.go:
  1. package message

  2. import (
  3.         "fmt"
  4.         //        "errors"
  5.         //        "github.com/pojoin/golis"
  6.         "sync"
  7. )

  8. var taskPoolOnce sync.Once

  9. type TaskInfo struct {
  10.         Cmd   *Command
  11.         MsgId string
  12. }

  13. type TaskPool struct {
  14.         WaitMap map[string]*TaskInfo
  15. }

  16. var taskPoolInstance *TaskPool

  17. func GetTaskPoolInstance() *TaskPool {
  18.         taskPoolOnce.Do(func() {
  19.                 fmt.Println("+++++++++++ taskPool instance +++++++")
  20.                 taskPoolInstance = &TaskPool{}
  21.         })
  22.         return taskPoolInstance
  23. }

  24. func (tp *TaskPool) Add(task *TaskInfo, msgId string) {
  25.         tp.WaitMap[msgId] = task
  26. }

  27. func (tp *TaskPool) Del(msgId string) {
  28.         delete(tp.WaitMap, msgId)
  29. }


测试函数:
  1. package main

  2. import (
  3.         "fmt"
  4.         "message"
  5. )

  6. func main() {
  7.         fmt.Println("message test")
  8.         var cmddb1, cmddb2, cmddb3 *message.CommandDb
  9.         cmddb1 = message.GetCommandDbInstance()
  10.         s1 := fmt.Sprintf(" %d", cmddb1)
  11.         fmt.Println("cmddb1: ", s1)
  12.         cmddb2 = message.GetCommandDbInstance()
  13.         s2 := fmt.Sprintf(" %d", cmddb2)
  14.         fmt.Println("cmddb2: ", s2)
  15.         cmddb3 = message.GetCommandDbInstance()
  16.         s3 := fmt.Sprintf(" %d", cmddb3)
  17.         fmt.Println("cmddb3: ", s3)

  18.         var taskp1, taskp2, taskp3 *message.TaskPool
  19.         taskp1 = message.GetTaskPoolInstance()
  20.         t1 := fmt.Sprintf(" %d", taskp1)
  21.         fmt.Println("taskp1: ", t1)
  22.         taskp2 = message.GetTaskPoolInstance()
  23.         t2 := fmt.Sprintf(" %d", taskp2)
  24.         fmt.Println("taskp2: ", t2)
  25.         taskp3 = message.GetTaskPoolInstance()
  26.         t3 := fmt.Sprintf(" %d", taskp3)
  27.         fmt.Println("taskp3: ", t3)
  28. }



@yyy71cj @21ic小喇叭 @dong_abc @ayb_ice @Simon21ic



 楼主| keer_zu 发表于 2016-12-2 20:03 | 显示全部楼层
  1. package message

  2. import (
  3.         "container/list"
  4.         "data_manager"
  5.         "encoding/json"
  6.         "errors"
  7.         "fmt"
  8.         "sync"

  9.         "github.com/pojoin/golis"
  10. )

  11. var once sync.Once

  12. type CommandProperty int

  13. type Command interface {
  14.         BuildResponse(info interface{}) (string, error)
  15.         CommandHandle(session *golis.Iosession, CmdInfo interface{}) error
  16.         GetCommandName() string
  17.         IsProvidedResult() bool
  18. }

  19. type CommandAttribute struct {
  20.         CommandName      string
  21.         IsProvidedResult bool //CommandProperty
  22. }

  23. ////////////////////////////dmc  command ////////////////////////////
  24. ////////////////////// dmc_register  /////////////////////
  25. type DmcRegist struct {
  26.         Command string `json:"command"`
  27.         MsgId   string `json:"msg_id"`
  28.         RoomId  int32  `json:"room_id"`
  29. }

  30. type DmcCommandRegist struct {
  31.         cmdAtt CommandAttribute
  32. }

  33. //////////////////////  dmc_heart_beat  //////////////////
  34. type DmcHeartBeat struct {
  35.         Command string `json:"command"`
  36.         MsgId   string `json:"msg_id"`
  37.         DmcId   int32  `json:"dmc_id"`
  38. }

  39. type DmcCommandHeartBeat struct {
  40.         cmdAtt CommandAttribute
  41. }

  42. ////////////////////// dmc_unregister //////////////////

  43. type DmcUnregister struct {
  44.         Command string `json:"command"`
  45.         MsgId   string `json:"msg_id"`
  46.         DmcId   int32  `json:"dmc_id"`
  47. }

  48. type DmcCommandUnregister struct {
  49.         cmdAtt CommandAttribute
  50. }

  51. ////////////////////// dmc_stream_query //////////////////
  52. type DmcStreamQuery struct {
  53.         Command    string `json:"command"`
  54.         MsgId      string `json:"msg_id"`
  55.         DmcId      int32  `json:"dmc_id"`
  56.         StreamName string `json:"stream_name"`
  57. }

  58. type DmcCommandStreamQuery struct {
  59.         cmdAtt CommandAttribute
  60. }

  61. ////////////////// dmc _all_stream_update ////////////////
  62. type DmcAllStreamUpdate struct {
  63.         Command        string                          `json:"command"`
  64.         MsgId          string                          `json:"msg_id"`
  65.         DmcId          int32                           `json:"dmc_id"`
  66.         StreamInfoList []data_manager.StreamAttributes `json:"stream_info"`
  67. }

  68. type DmcCommandAllStreamUpdate struct {
  69.         cmdAtt CommandAttribute
  70. }

  71. ////////////////// dmc _capability_update ////////////////
  72. type DmcCapabilityUpdate struct {
  73.         Command string            `json:"command"`
  74.         MsgId   string            `json:"msg_id"`
  75.         DmcId   int32             `json:"dmc_id"`
  76.         Cap     Capability        `json:"capability"`
  77.         NCap    NetworkCapability `json:"network_capability"`
  78.         Ld      Load              `json:"load"`
  79.         NLd     NetworkLoad       `json:"network_load"`
  80. }

  81. type DmcCommandCapabilityUpdate struct {
  82.         cmdAtt CommandAttribute
  83. }

  84. //////////////////// dmc _stream_ update ////////////////
  85. type DmcStreamUpdate struct {
  86.         Command string `json:"command"`
  87.         MsgId   string `json:"msg_id"`
  88.         DmcId   int32  `json:"dmc_id"`
  89.         ////////////////// StreamAttributes /////////////////
  90.         Name       string                       `json:"stream_name"`
  91.         Operate    data_manager.StreamOperate   `json:"operate"`
  92.         Status     data_manager.StreamState     `json:"status"`
  93.         Attributes data_manager.StreamAttribute `json:"attributes"`
  94.         Type       data_manager.StreamType      `json:"type"`
  95.         DmsInfo    []string                     `json:"dms_info"`
  96. }

  97. type DmcCommandStreamUpdate struct {
  98.         cmdAtt CommandAttribute
  99. }

  100. //////////////////// dmc_get_dms_request ////////////////
  101. type DmcGetDmsRequest struct {
  102.         Command string `json:"command"`
  103.         MsgId   string `json:"msg_id"`
  104.         DmcId   int32  `json:"dmc_id"`
  105. }

  106. type DmcCommandGetDmsRequest struct {
  107.         cmdAtt CommandAttribute
  108. }

  109. //////////////////////////////////////////////////////////////////

  110. //////////////////////////   gmc request & response   /////////////////////////////

  111. type GmcRegResponse struct {
  112.         Command string `json:"command"`
  113.         MsgId   string `json:"msg_id"`
  114.         DmcId   int32  `json:"dmc_id"`
  115. }

  116. type GmcResponse struct {
  117.         Command string `json:"command"`
  118.         MsgId   string `json:"msg_id"`
  119. }

  120. type GmcStreamQueryResult struct {
  121.         Command    string     `json:"command"`
  122.         MsgId      string     `json:"msg_id"`
  123.         Result     string     `json:"result"`
  124.         StreamName string     `json:"stream_name"`
  125.         DmsInfo    *list.List `json:"dms_info"`
  126. }

  127. ///////////////////////////////////////////////////////////////////////////////////

  128. func (dcr *DmcCommandRegist) BuildResponse(info interface{}) (string, error) {

  129.         return "abc", errors.New("cde")
  130. }

  131. func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  132.         fmt.Println("register command handle ........ ")
  133.         cmd := CmdInfo.(*DmcRegist)
  134.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " roomid:", cmd.RoomId)
  135.         dmc_instance := data_manager.GetDmcInstance()
  136.         dmc_id := dmc_instance.GetDmcId()
  137.         dmc_info := data_manager.DmcInfo{dmc_id, list.New(), list.New(), cmd.RoomId}
  138.         dmc_instance.AddDmcInfo(dmc_id, dmc_info)
  139.         gmcResponse := &GmcRegResponse{"gmc_reg_response", cmd.MsgId, dmc_id}

  140.         b, err := json.Marshal(gmcResponse)
  141.         if err != nil {
  142.                 fmt.Println("encoding faild")
  143.                 return errors.New("encoding faild")
  144.         } else {
  145.                 fmt.Println("encoded data : ")
  146.                 //fmt.Println(b)
  147.                 fmt.Println(string(b))
  148.         }

  149.         buf := make([]byte, len(b)+1)
  150.         copy(buf, b[:])
  151.         buf[len(b)] = 0x00

  152.         fmt.Println("------------- Session write frame: ---")

  153.         session.Write(buf)

  154.         return nil
  155. }

  156. func (dcr *DmcCommandRegist) GetCommandName() string {
  157.         return dcr.cmdAtt.CommandName
  158. }

  159. func (dcr *DmcCommandRegist) IsProvidedResult() bool {
  160.         return dcr.cmdAtt.IsProvidedResult
  161. }

  162. ///////////////////// dmc_heart_beat ////////////////////////

  163. func (dcr *DmcCommandHeartBeat) BuildResponse(info interface{}) (string, error) {

  164.         return "abc", errors.New("cde")
  165. }

  166. func (dcr *DmcCommandHeartBeat) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  167.         fmt.Println("heart beat command handle ........ ")
  168.         return nil
  169. }

  170. func (dcr *DmcCommandHeartBeat) GetCommandName() string {
  171.         return dcr.cmdAtt.CommandName
  172. }

  173. func (dcr *DmcCommandHeartBeat) IsProvidedResult() bool {
  174.         return dcr.cmdAtt.IsProvidedResult
  175. }

  176. ////////////////////// dmc_unregister //////////////////
  177. func (dcr *DmcCommandUnregister) BuildResponse(info interface{}) (string, error) {

  178.         return "abc", errors.New("cde")
  179. }

  180. func (dcr *DmcCommandUnregister) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  181.         fmt.Println("unregister command handle ........ ")
  182.         cmd := CmdInfo.(*DmcUnregister)
  183.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId)
  184.         dmc_instance := data_manager.GetDmcInstance()

  185.         dmc_instance.DelDmcInfo(cmd.DmcId)
  186.         gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

  187.         b, err := json.Marshal(gmcResponse)
  188.         if err != nil {
  189.                 fmt.Println("encoding faild")
  190.                 return errors.New("encoding faild")
  191.         } else {
  192.                 fmt.Println("encoded data : ")
  193.                 //fmt.Println(b)
  194.                 fmt.Println(string(b))
  195.         }

  196.         buf := make([]byte, len(b)+1)
  197.         copy(buf, b[:])
  198.         buf[len(b)] = 0x00

  199.         fmt.Println("------------- Session write frame: ---")

  200.         session.Write(buf)
  201.         return nil
  202. }

  203. func (dcr *DmcCommandUnregister) GetCommandName() string {
  204.         return dcr.cmdAtt.CommandName
  205. }

  206. func (dcr *DmcCommandUnregister) IsProvidedResult() bool {
  207.         return dcr.cmdAtt.IsProvidedResult
  208. }

  209. ////////////////////// dmc_stream_query //////////////////
  210. func (dcr *DmcCommandStreamQuery) BuildResponse(info interface{}) (string, error) {

  211.         return "abc", errors.New("cde")
  212. }

  213. func (dcr *DmcCommandStreamQuery) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  214.         fmt.Println("stream query command handle ........ ")
  215.         cmd := CmdInfo.(*DmcStreamQuery)
  216.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId, "streamname:", cmd.StreamName)
  217.         stream_instance := data_manager.GetStreamInstance()
  218.         stream_info, result := stream_instance.GetStreamInfo(cmd.StreamName)
  219.         var queryresponse *GmcStreamQueryResult
  220.         if result == true {
  221.                 queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Found", cmd.StreamName, stream_info.DmsInfo}
  222.         } else {
  223.                 queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Not Found", cmd.StreamName, nil}
  224.         }

  225.         b, err := json.Marshal(queryresponse)
  226.         if err != nil {
  227.                 fmt.Println("encoding faild")
  228.                 return errors.New("encoding faild")
  229.         } else {
  230.                 fmt.Println("encoded data : ")
  231.                 //fmt.Println(b)
  232.                 fmt.Println(string(b))
  233.         }

  234.         buf := make([]byte, len(b)+1)
  235.         copy(buf, b[:])
  236.         buf[len(b)] = 0x00

  237.         fmt.Println("------------- Session write frame: ---")

  238.         session.Write(buf)
  239.         return nil
  240. }

  241. func (dcr *DmcCommandStreamQuery) GetCommandName() string {
  242.         return dcr.cmdAtt.CommandName
  243. }

  244. func (dcr *DmcCommandStreamQuery) IsProvidedResult() bool {
  245.         return dcr.cmdAtt.IsProvidedResult
  246. }

  247. ////////////////// dmc_all_stream_update ////////////////
  248. func (dcr *DmcCommandAllStreamUpdate) BuildResponse(info interface{}) (string, error) {

  249.         return "abc", errors.New("cde")
  250. }

  251. func (dcr *DmcCommandAllStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  252.         fmt.Println("all stream  update command handle ........ ")
  253.         cmd := CmdInfo.(*DmcAllStreamUpdate)
  254.         fmt.Printf("------------------ len=%d cap=%d slice=%v\n", len(cmd.StreamInfoList), cap(cmd.StreamInfoList), cmd.StreamInfoList)

  255.         return nil
  256. }

  257. func (dcr *DmcCommandAllStreamUpdate) GetCommandName() string {
  258.         return dcr.cmdAtt.CommandName
  259. }

  260. func (dcr *DmcCommandAllStreamUpdate) IsProvidedResult() bool {
  261.         return dcr.cmdAtt.IsProvidedResult
  262. }

  263. ////////////////// dmc_capability_update ////////////////
  264. func (dcr *DmcCommandCapabilityUpdate) BuildResponse(info interface{}) (string, error) {

  265.         return "abc", errors.New("cde")
  266. }

  267. func (dcr *DmcCommandCapabilityUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  268.         fmt.Println("capability  update command handle ........ ")
  269.         return nil
  270. }

  271. func (dcr *DmcCommandCapabilityUpdate) GetCommandName() string {
  272.         return dcr.cmdAtt.CommandName
  273. }

  274. func (dcr *DmcCommandCapabilityUpdate) IsProvidedResult() bool {
  275.         return dcr.cmdAtt.IsProvidedResult
  276. }

  277. //////////////////// dmc_stream_update ////////////////
  278. func (dcr *DmcCommandStreamUpdate) BuildResponse(info interface{}) (string, error) {

  279.         return "abc", errors.New("cde")
  280. }

  281. func (dcr *DmcCommandStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  282.         fmt.Println("stream  update command handle ........ ")
  283.         return nil
  284. }

  285. func (dcr *DmcCommandStreamUpdate) GetCommandName() string {
  286.         return dcr.cmdAtt.CommandName
  287. }

  288. func (dcr *DmcCommandStreamUpdate) IsProvidedResult() bool {
  289.         return dcr.cmdAtt.IsProvidedResult
  290. }

  291. //////////////////// dmc_get_dms_request ////////////////
  292. func (dcr *DmcCommandGetDmsRequest) BuildResponse(info interface{}) (string, error) {

  293.         return "abc", errors.New("cde")
  294. }

  295. func (dcr *DmcCommandGetDmsRequest) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  296.         fmt.Println("get dms request command handle ........ ")
  297.         return nil
  298. }

  299. func (dcr *DmcCommandGetDmsRequest) GetCommandName() string {
  300.         return dcr.cmdAtt.CommandName
  301. }

  302. func (dcr *DmcCommandGetDmsRequest) IsProvidedResult() bool {
  303.         return dcr.cmdAtt.IsProvidedResult
  304. }

  305. ////////////////////////////////////////////////// CommandDb /////////////////////////////////////////////////////////
  306. type CommandDb struct {
  307.         CommandMap  map[string]Command
  308.         JsonReflect *JsonReflectMap
  309. }

  310. var commandDbInstance *CommandDb

  311. func GetCommandDbInstance() *CommandDb {
  312.         once.Do(func() {
  313.                 commandDbInstance = &CommandDb{}
  314.                 commandDbInstance.CommandMap = make(map[string]Command)
  315.                 commandDbInstance.JsonReflect = Json()
  316.                 //////////////////////////////////////// add command /////////////////////////////////////////

  317.                 /////////////////////////////////////// dmc_register /////////////////////////////
  318.                 commandDbInstance.JsonReflect.RegisterName("dmc_register", DmcRegist{})
  319.                 commandDbInstance.AddCommand(&DmcCommandRegist{cmdAtt: CommandAttribute{CommandName: "dmc_register", IsProvidedResult: false}}, "dmc_register")

  320.                 ///////////////////////////////////// dmc_heart_beat /////////////////////////////
  321.                 commandDbInstance.JsonReflect.RegisterName("dmc_heart_beat", DmcHeartBeat{})
  322.                 commandDbInstance.AddCommand(&DmcCommandHeartBeat{cmdAtt: CommandAttribute{CommandName: "dmc_heart_beat", IsProvidedResult: false}}, "dmc_heart_beat")

  323.                 ///////////////////////////////////// dmc_unregister /////////////////////////////
  324.                 commandDbInstance.JsonReflect.RegisterName("dmc_unregister", DmcUnregister{})
  325.                 commandDbInstance.AddCommand(&DmcCommandUnregister{cmdAtt: CommandAttribute{CommandName: "dmc_unregister", IsProvidedResult: false}}, "dmc_unregister")

  326.                 ///////////////////////////////////// dmc_stream_query /////////////////////////////
  327.                 commandDbInstance.JsonReflect.RegisterName("dmc_stream_query", DmcStreamQuery{})
  328.                 commandDbInstance.AddCommand(&DmcCommandStreamQuery{cmdAtt: CommandAttribute{CommandName: "dmc_stream_query", IsProvidedResult: false}}, "dmc_stream_query")

  329.                 ///////////////////////////////////// dmc_all_stream_update /////////////////////////////
  330.                 commandDbInstance.JsonReflect.RegisterName("dmc_all_stream_update", DmcAllStreamUpdate{})
  331.                 commandDbInstance.AddCommand(&DmcCommandAllStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_all_stream_update", IsProvidedResult: false}}, "dmc_all_stream_update")

  332.                 ///////////////////////////////////// dmc_capability_update /////////////////////////////
  333.                 commandDbInstance.JsonReflect.RegisterName("dmc_capability_update", DmcCapabilityUpdate{})
  334.                 commandDbInstance.AddCommand(&DmcCommandCapabilityUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_capability_update", IsProvidedResult: false}}, "dmc_capability_update")

  335.                 ///////////////////////////////////// dmc_stream_update /////////////////////////////
  336.                 commandDbInstance.JsonReflect.RegisterName("dmc_stream_update", DmcStreamUpdate{})
  337.                 commandDbInstance.AddCommand(&DmcCommandStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_stream_update", IsProvidedResult: false}}, "dmc_stream_update")

  338.                 ///////////////////////////////////// dmc_get_dms_request /////////////////////////////
  339.                 commandDbInstance.JsonReflect.RegisterName("dmc_get_dms_request", DmcGetDmsRequest{})
  340.                 commandDbInstance.AddCommand(&DmcCommandGetDmsRequest{cmdAtt: CommandAttribute{CommandName: "dmc_get_dms_request", IsProvidedResult: true}}, "dmc_get_dms_request")

  341.         })
  342.         return commandDbInstance
  343. }

  344. func (cdb *CommandDb) AddCommand(cmd Command, cmdName string) {
  345.         cdb.CommandMap[cmdName] = cmd
  346. }

  347. func (cdb *CommandDb) GetCommand(name string) (Command, error) {

  348.         if cdb.CommandMap[name] != nil {
  349.                 return cdb.CommandMap[name], nil
  350.         }

  351.         err := errors.New("This command is not exist!")

  352.         return nil, err
  353. }


dong_abc 发表于 2016-12-3 16:40 | 显示全部楼层
其实go语言应用很普遍。
dong_abc 发表于 2016-12-4 00:01 | 显示全部楼层
我觉得楼主没必要在这里讨论这个,你想把梳子卖给和尚,这很励志,但没什么意义!
 楼主| keer_zu 发表于 2016-12-5 08:23 | 显示全部楼层
dong_abc 发表于 2016-12-4 00:01
我觉得楼主没必要在这里讨论这个,你想把梳子卖给和尚,这很励志,但没什么意义! ...

 楼主| keer_zu 发表于 2016-12-5 08:23 | 显示全部楼层
dong_abc 发表于 2016-12-3 16:40
其实go语言应用很普遍。

是的
 楼主| keer_zu 发表于 2016-12-5 16:05 | 显示全部楼层
继续完善  command.go
Part 1:

  1. package message

  2. import (
  3.         "container/list"
  4.         "data_manager"
  5.         "encoding/json"
  6.         "errors"
  7.         "fmt"
  8.         "sync"

  9.         "github.com/pojoin/golis"
  10. )

  11. var once sync.Once

  12. type CommandProperty int

  13. type Command interface {
  14.         //BuildResponse(info interface{}) (string, error)
  15.         CommandHandle(session *golis.Iosession, CmdInfo interface{}) error
  16.         GetCommandName() string
  17.         IsProvidedResult() bool
  18. }

  19. type CommandAttribute struct {
  20.         CommandName      string
  21.         IsProvidedResult bool //CommandProperty
  22. }

  23. ////////////////////////////dmc  command ////////////////////////////
  24. ////////////////////// dmc_register  /////////////////////
  25. type DmcRegist struct {
  26.         Command string `json:"command"`
  27.         MsgId   string `json:"msg_id"`
  28.         RoomId  int32  `json:"room_id"`
  29. }

  30. type DmcCommandRegist struct {
  31.         cmdAtt CommandAttribute
  32. }

  33. //////////////////////  dmc_heart_beat  //////////////////
  34. type DmcHeartBeat struct {
  35.         Command string `json:"command"`
  36.         MsgId   string `json:"msg_id"`
  37.         DmcId   int32  `json:"dmc_id"`
  38. }

  39. type DmcCommandHeartBeat struct {
  40.         cmdAtt CommandAttribute
  41. }

  42. ////////////////////// dmc_unregister //////////////////

  43. type DmcUnregister struct {
  44.         Command string `json:"command"`
  45.         MsgId   string `json:"msg_id"`
  46.         DmcId   int32  `json:"dmc_id"`
  47. }

  48. type DmcCommandUnregister struct {
  49.         cmdAtt CommandAttribute
  50. }

  51. ////////////////////// dmc_stream_query //////////////////
  52. type DmcStreamQuery struct {
  53.         Command    string `json:"command"`
  54.         MsgId      string `json:"msg_id"`
  55.         DmcId      int32  `json:"dmc_id"`
  56.         StreamName string `json:"stream_name"`
  57. }

  58. type DmcCommandStreamQuery struct {
  59.         cmdAtt CommandAttribute
  60. }

  61. ////////////////// dmc _all_stream_update ////////////////
  62. type DmcAllStreamUpdate struct {
  63.         Command        string                          `json:"command"`
  64.         MsgId          string                          `json:"msg_id"`
  65.         DmcId          int32                           `json:"dmc_id"`
  66.         StreamInfoList []data_manager.StreamAttributes `json:"stream_info"`
  67. }

  68. type DmcCommandAllStreamUpdate struct {
  69.         cmdAtt CommandAttribute
  70. }

  71. ////////////////// dmc _capability_update ////////////////
  72. type DmcCapabilityUpdate struct {
  73.         Command string            `json:"command"`
  74.         MsgId   string            `json:"msg_id"`
  75.         DmcId   int32             `json:"dmc_id"`
  76.         Cap     Capability        `json:"capability"`
  77.         NCap    NetworkCapability `json:"network_capability"`
  78.         Ld      Load              `json:"load"`
  79.         NLd     NetworkLoad       `json:"network_load"`
  80. }

  81. type DmcCommandCapabilityUpdate struct {
  82.         cmdAtt CommandAttribute
  83. }

  84. //////////////////// dmc _stream_ update ////////////////
  85. type DmcStreamUpdate struct {
  86.         Command string `json:"command"`
  87.         MsgId   string `json:"msg_id"`
  88.         DmcId   int32  `json:"dmc_id"`
  89.         ////////////////// StreamAttributes /////////////////
  90.         Operate    data_manager.StreamOperate   `json:"operate"`
  91.         Name       string                       `json:"stream_name"`
  92.         Status     data_manager.StreamState     `json:"status"`
  93.         Attributes data_manager.StreamAttribute `json:"attributes"`
  94.         Type       data_manager.StreamType      `json:"type"`
  95.         DmsInfo    []string                     `json:"dms_info"`
  96. }

  97. type DmcCommandStreamUpdate struct {
  98.         cmdAtt CommandAttribute
  99. }

  100. //////////////////// dmc_get_dms_request ////////////////
  101. type DmcGetDmsRequest struct {
  102.         Command string                  `json:"command"`
  103.         MsgId   string                  `json:"msg_id"`
  104.         DmcId   int32                   `json:"dmc_id"`
  105.         Type    data_manager.StreamType `json:"type"`
  106. }

  107. type DmcCommandGetDmsRequest struct {
  108.         cmdAtt CommandAttribute
  109. }

  110. ////////// dmc_get_dms_response /////////////
  111. type DmcGetDmsResponse struct {
  112.         Command string   `json:"command"`
  113.         MsgId   string   `json:"msg_id"`
  114.         DmcId   int32    `json:"dmc_id"`
  115.         DmsInfo []string `json:"dms_info"`
  116. }

  117. type DmcCommandGetDmsResponse struct {
  118.         cmdAtt CommandAttribute
  119. }

  120. //////////////////////////////////////////////////////////////////

  121. //////////////////////////   gmc request & response   /////////////////////////////

  122. func AddFrameTail(input []byte) []byte {
  123.         buf := make([]byte, len(input)+1)
  124.         copy(buf, input[:])
  125.         buf[len(input)] = 0x00

  126.         return buf
  127. }

  128. func JsonMarshal(msgStruct interface{}) ([]byte, error) {
  129.         b, err := json.Marshal(msgStruct)
  130.         if err != nil {
  131.                 fmt.Println("encoding faild")
  132.                 return nil, errors.New("encoding faild")
  133.         } else {
  134.                 fmt.Println("encoded data : ")
  135.                 //fmt.Println(b)
  136.                 fmt.Println(string(b))
  137.         }

  138.         return b, err
  139. }

  140. type GmcMessage interface {
  141.         BuildMessage() ([]byte, error)
  142. }

  143. /////// gmc_reg_response ///////
  144. type GmcRegResponse struct {
  145.         Command string `json:"command"`
  146.         MsgId   string `json:"msg_id"`
  147.         DmcId   int32  `json:"dmc_id"`
  148. }

  149. func (gm *GmcRegResponse) BuildMessage() ([]byte, error) {

  150.         //gmcRegResponse := &GmcRegResponse{"gmc_reg_response", gm.MsgId, gm.DmcId}

  151.         b, err := JsonMarshal(*gm)
  152.         if b == nil {
  153.                 return b, err

  154.         }

  155.         buf := AddFrameTail(b)

  156.         return buf, nil
  157. }

  158. /////// gmc_response ///////
  159. type GmcResponse struct {
  160.         Command string `json:"command"`
  161.         MsgId   string `json:"msg_id"`
  162. }

  163. func (gm *GmcResponse) BuildMessage() ([]byte, error) {
  164.         //gmcResponse := &GmcResponse{"gmc_response", gm.MsgId}

  165.         b, err := JsonMarshal(*gm)
  166.         if b == nil {
  167.                 return b, err

  168.         }

  169.         buf := AddFrameTail(b)

  170.         return buf, nil
  171. }

  172. /////// gmc_stream_query_result ///////

  173. type GmcStreamQueryResult struct {
  174.         Command    string     `json:"command"`
  175.         MsgId      string     `json:"msg_id"`
  176.         Result     string     `json:"result"`
  177.         StreamName string     `json:"stream_name"`
  178.         DmsInfo    *list.List `json:"dms_info"`
  179. }

  180. func (gm *GmcStreamQueryResult) BuildMessage() ([]byte, error) {

  181.         b, err := JsonMarshal(*gm)
  182.         if b == nil {
  183.                 return b, err

  184.         }

  185.         buf := AddFrameTail(b)

  186.         return buf, nil
  187. }

  188. //////// gmc_get_dms_request //////////

  189. type GmcGetDmsRequest struct {
  190.         Command string `json:"command"`
  191.         MsgId   string `json:"msg_id"`
  192. }

  193. func (gm *GmcGetDmsRequest) BuildMessage() ([]byte, error) {
  194.         //gmcResponse := &GmcGetDmsRequest{"gmc_get_dms_request", gm.MsgId}

  195.         b, err := JsonMarshal(*gm)
  196.         if b == nil {
  197.                 return b, err

  198.         }

  199.         buf := AddFrameTail(b)

  200.         return buf, nil
  201. }

  202. /////////// gmc_get_dms_response /////////
  203. type GmcGetDmsResponse struct {
  204.         Command string   `json:"command"`
  205.         MsgId   string   `json:"msg_id"`
  206.         DmcId   int32    `json:"dmc_id"`
  207.         DmsInfo []string `json:"dms_info"`
  208. }

  209. func (gm *GmcGetDmsResponse) BuildMessage() ([]byte, error) {

  210.         b, err := JsonMarshal(*gm)
  211.         if b == nil {
  212.                 return b, err

  213.         }

  214.         buf := AddFrameTail(b)

  215.         return buf, nil
  216. }

  217. /////// gmc_stream_published_notify //////

  218. type GmcStreamPublishedNotify struct {
  219.         Command    string   `json:"command"`
  220.         MsgId      string   `json:"msg_id"`
  221.         StreamName string   `json:"stream_name"`
  222.         DmsInfo    []string `json:"dms_info"`
  223. }

  224. func (gm *GmcStreamPublishedNotify) BuildMessage() ([]byte, error) {

  225.         b, err := JsonMarshal(*gm)
  226.         if b == nil {
  227.                 return b, err

  228.         }

  229.         buf := AddFrameTail(b)

  230.         return buf, nil
  231. }

  232. /////////// func BuildGmcMessage ////////////
  233. func BuildGmcMessage(gmcMsg GmcMessage) ([]byte, error) {

  234.         msg, err := gmcMsg.BuildMessage()
  235.         if err != nil {
  236.                 return nil, err
  237.         }
  238.         return msg, nil
  239. }

  240. ///////////////////////////////////////////////////////////////////////////////////

  241. func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  242.         fmt.Println("register command handle ........ ")
  243.         cmd := CmdInfo.(*DmcRegist)

  244.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " roomid:", cmd.RoomId)
  245.         dmc_instance := data_manager.GetDmcInstance()
  246.         dmc_id := dmc_instance.GetDmcId()

  247.         dmc_info := data_manager.DmcInfo{dmc_id, list.New(), list.New(), cmd.RoomId, session}
  248.         dmc_instance.AddDmcInfo(dmc_id, dmc_info)

  249.         gmcResponse := &GmcRegResponse{"gmc_reg_response", cmd.MsgId, dmc_id}

  250.         buf, err := BuildGmcMessage(gmcResponse)
  251.         if err != nil {
  252.                 return err
  253.         }
  254.         fmt.Println("------------- Session write frame: ---")

  255.         session.Write(buf)

  256.         return nil
  257. }

  258. func (dcr *DmcCommandRegist) GetCommandName() string {
  259.         return dcr.cmdAtt.CommandName
  260. }

  261. func (dcr *DmcCommandRegist) IsProvidedResult() bool {
  262.         return dcr.cmdAtt.IsProvidedResult
  263. }

  264. ///////////////////// dmc_heart_beat ////////////////////////

  265. func (dcr *DmcCommandHeartBeat) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  266.         fmt.Println("heart beat command handle ........ ")
  267.         cmd := CmdInfo.(*DmcHeartBeat)
  268.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId)

  269.         return nil
  270. }

  271. func (dcr *DmcCommandHeartBeat) GetCommandName() string {
  272.         return dcr.cmdAtt.CommandName
  273. }

  274. func (dcr *DmcCommandHeartBeat) IsProvidedResult() bool {
  275.         return dcr.cmdAtt.IsProvidedResult
  276. }

  277. ////////////////////// dmc_unregister //////////////////

  278. func (dcr *DmcCommandUnregister) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  279.         fmt.Println("unregister command handle ........ ")
  280.         cmd := CmdInfo.(*DmcUnregister)
  281.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId)
  282.         dmc_instance := data_manager.GetDmcInstance()

  283.         dmc_instance.DelDmcInfo(cmd.DmcId)
  284.         gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

  285.         buf, err := BuildGmcMessage(gmcResponse)
  286.         if err != nil {
  287.                 return err
  288.         }
  289.         fmt.Println("------------- Session write frame: ---")

  290.         session.Write(buf)
  291.         return nil
  292. }

  293. func (dcr *DmcCommandUnregister) GetCommandName() string {
  294.         return dcr.cmdAtt.CommandName
  295. }

  296. func (dcr *DmcCommandUnregister) IsProvidedResult() bool {
  297.         return dcr.cmdAtt.IsProvidedResult
  298. }

  299. ////////////////////// dmc_stream_query //////////////////

  300. func (dcr *DmcCommandStreamQuery) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  301.         fmt.Println("stream query command handle ........ ")
  302.         cmd := CmdInfo.(*DmcStreamQuery)
  303.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId, "streamname:", cmd.StreamName)
  304.         stream_instance := data_manager.GetStreamInstance()
  305.         stream_info, result := stream_instance.GetStreamInfo(cmd.StreamName)
  306.         var queryresponse *GmcStreamQueryResult
  307.         if result == true {
  308.                 queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Found", cmd.StreamName, stream_info.DmsInfo}
  309.         } else {
  310.                 queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Not Found", cmd.StreamName, nil}
  311.         }

  312.         b, err := json.Marshal(queryresponse)
  313.         if err != nil {
  314.                 fmt.Println("encoding faild")
  315.                 return errors.New("encoding faild")
  316.         } else {
  317.                 fmt.Println("encoded data : ")
  318.                 //fmt.Println(b)
  319.                 fmt.Println(string(b))
  320.         }

  321.         buf := make([]byte, len(b)+1)
  322.         copy(buf, b[:])
  323.         buf[len(b)] = 0x00

  324.         fmt.Println("------------- Session write frame: ---")

  325.         session.Write(buf)
  326.         return nil
  327. }

  328. func (dcr *DmcCommandStreamQuery) GetCommandName() string {
  329.         return dcr.cmdAtt.CommandName
  330. }

  331. func (dcr *DmcCommandStreamQuery) IsProvidedResult() bool {
  332.         return dcr.cmdAtt.IsProvidedResult
  333. }

  334. ////////////////// dmc_all_stream_update ////////////////

  335. func (dcr *DmcCommandAllStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  336.         fmt.Println("all stream  update command handle ........ ")
  337.         cmd := CmdInfo.(*DmcAllStreamUpdate)
  338.         fmt.Printf("------------------ len=%d cap=%d slice=%v\n", len(cmd.StreamInfoList), cap(cmd.StreamInfoList), cmd.StreamInfoList)
  339.         fmt.Println("cmd:", cmd.Command, " dmc id:", cmd.DmcId, " msg id:", cmd.MsgId)
  340.         stream_instance := data_manager.GetStreamInstance()
  341.         stream_lst := cmd.StreamInfoList
  342.         for _, stream_info := range stream_lst {
  343.                 temp_stream_info := data_manager.NewStreamInfo(stream_info.Name, cmd.DmcId, stream_info.State, stream_info.Attributes, stream_info.Type, list.New())
  344.                 stream_instance.AddStreamInfo(stream_info.Name, temp_stream_info)
  345.         }

  346.         gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

  347.         buf, err := BuildGmcMessage(gmcResponse)
  348.         if err != nil {
  349.                 return err
  350.         }
  351.         fmt.Println("------------- Session write frame: ---")

  352.         session.Write(buf)
  353.         return nil
  354. }

  355. func (dcr *DmcCommandAllStreamUpdate) GetCommandName() string {
  356.         return dcr.cmdAtt.CommandName
  357. }

  358. func (dcr *DmcCommandAllStreamUpdate) IsProvidedResult() bool {
  359.         return dcr.cmdAtt.IsProvidedResult
  360. }

  361. ////////////////// dmc_capability_update ////////////////

  362. func (dcr *DmcCommandCapabilityUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  363.         fmt.Println("capability  update command handle ........ ")
  364.         cmd := CmdInfo.(*DmcCapabilityUpdate)
  365.         fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId, " cap item:", cmd.Cap.Item, " ld item", cmd.Ld.Item, " nld item:", cmd.NLd.Item)

  366.         return nil
  367. }

  368. func (dcr *DmcCommandCapabilityUpdate) GetCommandName() string {
  369.         return dcr.cmdAtt.CommandName
  370. }

  371. func (dcr *DmcCommandCapabilityUpdate) IsProvidedResult() bool {
  372.         return dcr.cmdAtt.IsProvidedResult
  373. }

  374. //////////////////// dmc_stream_update ////////////////

  375. func (dcr *DmcCommandStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  376.         fmt.Println("stream  update command handle ........ ")
  377.         cmd := CmdInfo.(*DmcStreamUpdate)
  378.         fmt.Println(" cmd:", cmd.Command, " dmc id:", cmd.DmcId, " msg id:", cmd.MsgId, " stream name:", cmd.Name)
  379.         stream_instance := data_manager.GetStreamInstance()
  380.         if cmd.Operate == data_manager.ADDStream {
  381.                 temp_stream_info := data_manager.NewStreamInfo(cmd.Name, cmd.DmcId, cmd.Status, cmd.Attributes, cmd.Type, list.New())
  382.                 stream_instance.AddStreamInfo(cmd.Name, temp_stream_info)
  383.         } else if cmd.Operate == data_manager.DELStream {
  384.                 stream_instance.DelStreamInfo(cmd.Name)

  385.         } else {
  386.                 temp_stream_info := data_manager.NewStreamInfo(cmd.Name, cmd.DmcId, cmd.Status, cmd.Attributes, cmd.Type, list.New())
  387.                 stream_instance.ModStreamInfo(cmd.Name, temp_stream_info)
  388.         }

  389.         gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

  390.         buf, err := BuildGmcMessage(gmcResponse)
  391.         if err != nil {
  392.                 return err
  393.         }
  394.         fmt.Println("------------- Session write frame: ---")

  395.         session.Write(buf)

  396.         return nil
  397. }

  398. func (dcr *DmcCommandStreamUpdate) GetCommandName() string {
  399.         return dcr.cmdAtt.CommandName
  400. }

  401. func (dcr *DmcCommandStreamUpdate) IsProvidedResult() bool {
  402.         return dcr.cmdAtt.IsProvidedResult
  403. }

  404. //////////////////// dmc_get_dms_request ////////////////

  405. func (dcr *DmcCommandGetDmsRequest) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  406.         fmt.Println("get dms request command handle ........ ")
  407.         cmd := CmdInfo.(*DmcGetDmsRequest)
  408.         fmt.Println(" cmd:", cmd.Command, " msg id:", cmd.MsgId, " dmc id:", cmd.DmcId)

  409.         dmcManager := data_manager.GetDmcInstance()
  410.         dmc, err1 := dmcManager.GetDmc(data_manager.GET_A_USEFUL_DMS)
  411.         if err1 != nil {
  412.                 return errors.New("source dmc session is nil")
  413.         }

  414.         session_source_dmc := dmc.Session

  415.         gmcGetDmsRequest := &GmcGetDmsRequest{"gmc_get_dms_request", cmd.MsgId}
  416.         buf, err := BuildGmcMessage(gmcGetDmsRequest)
  417.         if err != nil {
  418.                 return err
  419.         }
  420.         fmt.Println("------------- Session write gmcGetDmsRequest frame: ---")

  421.         session_source_dmc.Write(buf)

  422.         return nil
  423. }

  424. func (dcr *DmcCommandGetDmsRequest) GetCommandName() string {
  425.         return dcr.cmdAtt.CommandName
  426. }

  427. func (dcr *DmcCommandGetDmsRequest) IsProvidedResult() bool {
  428.         return dcr.cmdAtt.IsProvidedResult
  429. }


 楼主| keer_zu 发表于 2016-12-5 16:06 | 显示全部楼层
继续完善 command.go

Part 2:
  1. ////////// dmc_get_dms_response /////////////

  2. func (dcr *DmcCommandGetDmsResponse) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
  3.         fmt.Println("get DmcGetDmsResponse  command handle ........ ")
  4.         cmd := CmdInfo.(*DmcGetDmsResponse)
  5.         fmt.Println(" cmd:", cmd.Command, " msg id:", cmd.MsgId, " dmc id:", cmd.DmcId)

  6.         taskPool := GetTaskPoolInstance()

  7.         defer taskPool.Del(cmd.MsgId)

  8.         taskInfo, ok := taskPool.GetTaskInfo(cmd.MsgId)
  9.         if !ok {
  10.                 return errors.New("can not fand this task!")
  11.         }

  12.         gmcGetDmsReponse := &GmcGetDmsResponse{"gmc_get_dms_response", cmd.MsgId, cmd.DmcId, cmd.DmsInfo}
  13.         buf, err := BuildGmcMessage(gmcGetDmsReponse)
  14.         if err != nil {
  15.                 return err
  16.         }
  17.         fmt.Println("------------- Session write GmcGetDmsResponse frame: ---")

  18.         session_dms_request := taskInfo.Session
  19.         session_dms_request.Write(buf)

  20.         return nil
  21. }

  22. func (dcr *DmcCommandGetDmsResponse) GetCommandName() string {
  23.         return dcr.cmdAtt.CommandName
  24. }

  25. func (dcr *DmcCommandGetDmsResponse) IsProvidedResult() bool {
  26.         return dcr.cmdAtt.IsProvidedResult
  27. }

  28. ////////////////////////////////////////////////// CommandDb /////////////////////////////////////////////////////////
  29. type CommandDb struct {
  30.         CommandMap  map[string]Command
  31.         JsonReflect *JsonReflectMap
  32. }

  33. var commandDbInstance *CommandDb

  34. func GetCommandDbInstance() *CommandDb {
  35.         once.Do(func() {
  36.                 commandDbInstance = &CommandDb{}
  37.                 commandDbInstance.CommandMap = make(map[string]Command)
  38.                 commandDbInstance.JsonReflect = Json()
  39.                 //////////////////////////////////////// add command /////////////////////////////////////////

  40.                 /////////////////////////////////////// dmc_register /////////////////////////////
  41.                 commandDbInstance.JsonReflect.RegisterName("dmc_register", DmcRegist{})
  42.                 commandDbInstance.AddCommand(&DmcCommandRegist{cmdAtt: CommandAttribute{CommandName: "dmc_register", IsProvidedResult: false}}, "dmc_register")

  43.                 ///////////////////////////////////// dmc_heart_beat /////////////////////////////
  44.                 commandDbInstance.JsonReflect.RegisterName("dmc_heart_beat", DmcHeartBeat{})
  45.                 commandDbInstance.AddCommand(&DmcCommandHeartBeat{cmdAtt: CommandAttribute{CommandName: "dmc_heart_beat", IsProvidedResult: false}}, "dmc_heart_beat")

  46.                 ///////////////////////////////////// dmc_unregister /////////////////////////////
  47.                 commandDbInstance.JsonReflect.RegisterName("dmc_unregister", DmcUnregister{})
  48.                 commandDbInstance.AddCommand(&DmcCommandUnregister{cmdAtt: CommandAttribute{CommandName: "dmc_unregister", IsProvidedResult: false}}, "dmc_unregister")

  49.                 ///////////////////////////////////// dmc_stream_query /////////////////////////////
  50.                 commandDbInstance.JsonReflect.RegisterName("dmc_stream_query", DmcStreamQuery{})
  51.                 commandDbInstance.AddCommand(&DmcCommandStreamQuery{cmdAtt: CommandAttribute{CommandName: "dmc_stream_query", IsProvidedResult: false}}, "dmc_stream_query")

  52.                 ///////////////////////////////////// dmc_all_stream_update /////////////////////////////
  53.                 commandDbInstance.JsonReflect.RegisterName("dmc_all_stream_update", DmcAllStreamUpdate{})
  54.                 commandDbInstance.AddCommand(&DmcCommandAllStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_all_stream_update", IsProvidedResult: false}}, "dmc_all_stream_update")

  55.                 ///////////////////////////////////// dmc_capability_update /////////////////////////////
  56.                 commandDbInstance.JsonReflect.RegisterName("dmc_capability_update", DmcCapabilityUpdate{})
  57.                 commandDbInstance.AddCommand(&DmcCommandCapabilityUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_capability_update", IsProvidedResult: false}}, "dmc_capability_update")

  58.                 ///////////////////////////////////// dmc_stream_update /////////////////////////////
  59.                 commandDbInstance.JsonReflect.RegisterName("dmc_stream_update", DmcStreamUpdate{})
  60.                 commandDbInstance.AddCommand(&DmcCommandStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_stream_update", IsProvidedResult: false}}, "dmc_stream_update")

  61.                 ///////////////////////////////////// dmc_get_dms_request /////////////////////////////
  62.                 commandDbInstance.JsonReflect.RegisterName("dmc_get_dms_request", DmcGetDmsRequest{})
  63.                 commandDbInstance.AddCommand(&DmcCommandGetDmsRequest{cmdAtt: CommandAttribute{CommandName: "dmc_get_dms_request", IsProvidedResult: true}}, "dmc_get_dms_request")

  64.                 ///////////////////////////////////// dmc_get_dms_response ////////////////////////////
  65.                 commandDbInstance.JsonReflect.RegisterName("dmc_get_dms_response", DmcGetDmsResponse{})
  66.                 commandDbInstance.AddCommand(&DmcCommandGetDmsResponse{cmdAtt: CommandAttribute{CommandName: "dmc_get_dms_response", IsProvidedResult: false}}, "dmc_get_dms_response")
  67.         })
  68.         return commandDbInstance
  69. }

  70. func (cdb *CommandDb) AddCommand(cmd Command, cmdName string) {
  71.         cdb.CommandMap[cmdName] = cmd
  72. }

  73. func (cdb *CommandDb) GetCommand(name string) (Command, error) {

  74.         if cdb.CommandMap[name] != nil {
  75.                 return cdb.CommandMap[name], nil
  76.         }

  77.         err := errors.New("This command is not exist!")

  78.         return nil, err
  79. }
您需要登录后才可以回帖 登录 | 注册

本版积分规则

1488

主题

12949

帖子

55

粉丝
快速回复 在线客服 返回列表 返回顶部