client-tcp2.go 2.2 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(cf, localChannel, func(channel string, hostType tinymq.HostType) (hostInfo *tinymq.HostInfo, err error) {
  23. return host, nil
  24. }, func(client bool, proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  25. log.Println("[AuthFunc]", client, proto, version, channel, string(remoteAuth))
  26. return []byte("tinymq-client")
  27. // 从 remoteAuth 是否为空来判断是否需要返回信息
  28. // if len(remoteAuth) <= 0 {
  29. // // 客户端调用,返回验证信息
  30. // return []byte("tinymq")
  31. // } else {
  32. // // 服务端调用,返回验证token,或者其他信息
  33. // return nil
  34. // }
  35. }, func(client bool, proto string, version uint8, channel string, auth []byte) bool {
  36. log.Println("[CheckAuthFunc]", client, proto, version, channel, string(auth))
  37. return string(auth) == "tinymq-server"
  38. }, func(conn *tinymq.Line) {
  39. log.Println("connect state", conn.Channel(), conn.State(), time.Since(conn.Updated()))
  40. }, nil)
  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. }