client-tcp2.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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(proto string, version uint8, channel string, remoteAuth []byte) (auth []byte) {
  25. // 从 remoteAuth 是否为空来判断是否需要返回信息
  26. if len(remoteAuth) <= 0 {
  27. // 客户端调用,返回验证信息
  28. return []byte("tinymq")
  29. } else {
  30. // 服务端调用,返回验证token,或者其他信息
  31. return nil
  32. }
  33. }, func(proto string, version uint8, channel string, auth []byte) bool {
  34. return true
  35. }, func(conn *tinymq.Line) {
  36. log.Println("connect state", conn.Channel(), conn.State(), time.Since(conn.Updated()))
  37. })
  38. // 订阅频道
  39. hub.Subscribe(remoteFilter, "hello", func(request *tinymq.RequestData) (state uint8, result any) {
  40. log.Println("[client RECV]<-", string(request.Data))
  41. return 1, "tiny client"
  42. },
  43. )
  44. hub.Subscribe(remoteFilter, "nodata", func(request *tinymq.RequestData) (state uint8, result any) {
  45. log.Println("[client RECV]<-", string(request.Data))
  46. return 1, nil
  47. },
  48. )
  49. err := hub.ConnectToServer("/tinymq/server", true, nil)
  50. if err != nil {
  51. log.Fatalln("[client ConnectToServer ERROR]", err)
  52. }
  53. // 获取信息
  54. rsp := hub.GetOne(remoteFilter, "hello", []byte("hello from client, hello from client, hello from client"))
  55. if rsp.State != config.STATE_OK {
  56. log.Println("error state:", rsp.State)
  57. return
  58. }
  59. log.Println("[RESULT]<-", string(rsp.Data))
  60. time.Sleep(time.Second * 300)
  61. log.Println("client exit")
  62. }