client-tcp2.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //go:build ignore
  2. // +build ignore
  3. package main
  4. import (
  5. "log"
  6. "time"
  7. "git.me9.top/git/tinymq"
  8. "git.me9.top/git/tinymq/config"
  9. )
  10. func main() {
  11. cf := config.NewConfig()
  12. localChannel := "/tinymq/client/tcp2"
  13. remoteChannel := "/tinymq/server"
  14. remoteFilter := tinymq.StrChannelFilter(remoteChannel)
  15. host := &tinymq.HostInfo{
  16. Proto: "tcp",
  17. Version: 2,
  18. Host: "127.0.0.1",
  19. Port: 34222,
  20. Hash: "xor:1qaz2wsx3",
  21. }
  22. hub := tinymq.NewHub(
  23. cf,
  24. localChannel,
  25. func(channel string, hostType tinymq.HostType) (hostInfo *tinymq.HostInfo, err error) {
  26. return host, nil
  27. },
  28. func(client bool, proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  29. log.Println("[AuthFunc]", client, proto, version, channel, string(remoteAuth))
  30. return []byte("tinymq-client")
  31. },
  32. func(client bool, proto string, version uint8, channel string, auth []byte) bool {
  33. log.Println("[CheckAuthFunc]", client, proto, version, channel, string(auth))
  34. return string(auth) == "tinymq-server"
  35. },
  36. func(conn *tinymq.Line) {
  37. log.Println("connect state", conn.Channel(), conn.State(), time.Since(conn.Updated()))
  38. },
  39. nil,
  40. )
  41. // 订阅频道
  42. hub.Subscribe(remoteFilter, "hello", func(request *tinymq.RequestData) (state uint8, result any) {
  43. log.Println("[client RECV]<-", string(request.Data))
  44. return 1, "tiny client"
  45. },
  46. )
  47. hub.Subscribe(remoteFilter, "nodata", func(request *tinymq.RequestData) (state uint8, result any) {
  48. log.Println("[client RECV]<-", string(request.Data))
  49. return 1, nil
  50. },
  51. )
  52. err := hub.ConnectToServer("/tinymq/server", true, nil)
  53. if err != nil {
  54. log.Fatalln("[client ConnectToServer ERROR]", err)
  55. }
  56. // 获取信息
  57. rsp := hub.GetOne(remoteFilter, "hello", []byte("hello from client, hello from client, hello from client"))
  58. if rsp.State != config.STATE_OK {
  59. log.Println("error state:", rsp.State)
  60. return
  61. }
  62. log.Println("[RESULT]<-", string(rsp.Data))
  63. time.Sleep(time.Second * 300)
  64. log.Println("client exit")
  65. }