client-tcp2.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. "git.me9.top/git/tinymq/conn"
  10. )
  11. func main() {
  12. cf := config.NewConfig()
  13. localChannel := "/tinymq/client/tcp2"
  14. remoteChannel := "/tinymq/server"
  15. remoteFilter := tinymq.StrChannelFilter(remoteChannel)
  16. host := &conn.HostInfo{
  17. Proto: "tcp",
  18. Version: 2,
  19. Host: "127.0.0.1",
  20. Port: 34222,
  21. Hash: "xor:1qaz2wsx3",
  22. }
  23. hub := tinymq.NewHub(
  24. cf,
  25. localChannel,
  26. func(channel string, hostType tinymq.HostType) (hostInfo *conn.HostInfo, err error) {
  27. return host, nil
  28. },
  29. func(host *conn.HostInfo, proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  30. log.Println("[AuthFunc]", host, proto, version, channel, string(remoteAuth))
  31. return []byte("tinymq-client")
  32. },
  33. func(host *conn.HostInfo, proto string, version uint8, channel string, auth []byte) bool {
  34. log.Println("[CheckAuthFunc]", host, proto, version, channel, string(auth))
  35. return string(auth) == "tinymq-server"
  36. },
  37. func(conn *tinymq.Line) {
  38. log.Println("[Connect state change]", conn.Channel(), conn.State(), time.Since(conn.Started()))
  39. },
  40. )
  41. // 从过滤器到频道字符串
  42. hub.SetFilterToChannelFunc(func(filter tinymq.FilterFunc) (channel string) {
  43. return remoteChannel
  44. })
  45. // 订阅频道
  46. hub.Subscribe(remoteFilter, "hello", func(request *tinymq.RequestData) (state uint8, result any) {
  47. log.Println("[client RECV]<-", string(request.Data))
  48. return 1, "tiny client"
  49. },
  50. )
  51. hub.Subscribe(remoteFilter, "nodata", func(request *tinymq.RequestData) (state uint8, result any) {
  52. log.Println("[client RECV]<-", string(request.Data))
  53. return 1, nil
  54. },
  55. )
  56. // err := hub.ConnectToServer("/tinymq/server", true, nil)
  57. // if err != nil {
  58. // log.Fatalln("[client ConnectToServer ERROR]", err)
  59. // }
  60. // 获取信息
  61. rsp := hub.GetOne(remoteFilter, "hello", []byte("hello from client, hello from client, hello from client"))
  62. if rsp.State != tinymq.STATE_OK {
  63. log.Println("error state:", rsp.State)
  64. return
  65. }
  66. log.Println("[RESULT]<-", string(rsp.Data))
  67. log.Println("test finished")
  68. time.Sleep(time.Second * 30)
  69. log.Println("client exit")
  70. }