client-wsv2.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. localChannel := "/tinymq/client/wsv2"
  14. remoteChannel := "/tinymq/server"
  15. host := &tinymq.HostInfo{
  16. Proto: "ws",
  17. Version: 2,
  18. Host: "127.0.0.1",
  19. Port: 34211,
  20. // Path: "/tinymq",
  21. Path: "/tinymq-xor",
  22. Hash: "xor:1qaz2wsx3edc",
  23. }
  24. hub := tinymq.NewHub(cf, localChannel, func(channel string) (hostInfo *tinymq.HostInfo, err error) {
  25. return host, nil
  26. }, func(proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  27. // 从 remoteAuth 是否为空来判断是否需要返回信息
  28. if len(remoteAuth) <= 0 {
  29. // 客户端调用,返回验证信息
  30. return []byte("tinymq")
  31. } else {
  32. // 服务端调用,返回验证token,或者其他信息
  33. return nil
  34. }
  35. }, func(proto string, cversion uint8, hannel string, auth []byte) bool {
  36. return true
  37. }, func(conn *tinymq.Line) {
  38. log.Println("connect state", conn.Channel(), conn.State())
  39. })
  40. // 订阅频道
  41. hub.Subscribe(regexp.MustCompile(remoteChannel), "hello", func(request *tinymq.RequestData) (state uint8, result []byte) {
  42. log.Println("[client RECV]<-", string(request.Data))
  43. return 1, []byte("tiny client")
  44. },
  45. )
  46. hub.Subscribe(regexp.MustCompile(remoteChannel), "nodata", func(request *tinymq.RequestData) (state uint8, result []byte) {
  47. log.Println("[client RECV]<-", string(request.Data))
  48. return 1, nil
  49. },
  50. )
  51. err := hub.ConnectToServer(remoteChannel, true)
  52. if err != nil {
  53. log.Fatalln("[client ConnectToServer ERROR]", err)
  54. }
  55. // 获取信息
  56. rsp := hub.GetOne(regexp.MustCompile(remoteChannel), "hello", []byte("hello from client"))
  57. if rsp.State != config.STATE_OK {
  58. log.Println("error state:", rsp.State)
  59. return
  60. }
  61. log.Println("[RESULT]<-", string(rsp.Data))
  62. time.Sleep(time.Second * 5)
  63. hub.Push(regexp.MustCompile(remoteChannel), "hello", []byte(time.Now().GoString()))
  64. time.Sleep(time.Second * 300)
  65. log.Println("client exit")
  66. }