client-tcp2.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //go:build ignore
  2. // +build ignore
  3. package main
  4. import (
  5. "log"
  6. "regexp"
  7. "time"
  8. "git.me9.top/git/tinymq"
  9. "git.me9.top/git/tinymq/config"
  10. )
  11. func main() {
  12. cf := config.NewConfig()
  13. channel := "/tinymq/client/tcp2"
  14. host := &tinymq.HostInfo{
  15. Proto: "tcp",
  16. Version: 2,
  17. Host: "127.0.0.1",
  18. Port: 34222,
  19. Hash: "xor:1qaz2wsx3",
  20. }
  21. hub := tinymq.NewHub(cf, channel, func(channel string) (hostInfo *tinymq.HostInfo, err error) {
  22. return host, nil
  23. }, func(proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  24. // 从 remoteAuth 是否为空来判断是否需要返回信息
  25. if len(remoteAuth) <= 0 {
  26. // 客户端调用,返回验证信息
  27. return []byte("tinymq")
  28. } else {
  29. // 服务端调用,返回验证token,或者其他信息
  30. return nil
  31. }
  32. }, func(proto string, version uint8, channel string, auth []byte) bool {
  33. return true
  34. }, func(conn *tinymq.Line) {
  35. log.Println("connect state", conn.State())
  36. })
  37. // 订阅频道
  38. hub.Subscribe(regexp.MustCompile("/tinymq/server"), "hello", func(request *tinymq.RequestData) (state uint8, result []byte) {
  39. log.Println("[client RECV]<-", string(request.Data))
  40. return 1, []byte("tiny client")
  41. },
  42. )
  43. hub.Subscribe(regexp.MustCompile("/tinymq/server"), "nodata", func(request *tinymq.RequestData) (state uint8, result []byte) {
  44. log.Println("[client RECV]<-", string(request.Data))
  45. return 1, nil
  46. },
  47. )
  48. err := hub.ConnectToServer("/tinymq/server", true)
  49. if err != nil {
  50. log.Fatalln("[client ConnectToServer ERROR]", err)
  51. }
  52. // 获取信息
  53. rsp := hub.GetOne(regexp.MustCompile("/tinymq/server"), "hello", []byte("hello from client"))
  54. if rsp.State != config.STATE_OK {
  55. log.Println("error state:", rsp.State)
  56. return
  57. }
  58. log.Println("[RESULT]<-", string(rsp.Data))
  59. time.Sleep(time.Second * 300)
  60. log.Println("client exit")
  61. }