github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/extend/emqx/test/emqx_test.go (about)

     1  package test
     2  
     3  import (
     4  	"fmt"
     5  	mqtt "github.com/eclipse/paho.mqtt.golang"
     6  	"github.com/isyscore/isc-gobase/extend/emqx"
     7  	"net/url"
     8  	"os"
     9  	"strings"
    10  	"testing"
    11  	"time"
    12  )
    13  
    14  func TestCut(t *testing.T) {
    15  	fmt.Println(strings.Cut("oksfadf#sdf#fms", "#"))
    16  	fmt.Println(strings.Cut("oksfadfdffms", "#"))
    17  
    18  	urlFinal, _ := url.Parse("tcp://user:xxxsdf@localhost:8080")
    19  	fmt.Println(urlFinal.User)
    20  	fmt.Println(urlFinal.Path)
    21  	fmt.Println(urlFinal.Host)
    22  }
    23  
    24  var msgHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
    25  	fmt.Printf("TOPIC: %s\n", msg.Topic())
    26  	fmt.Printf("MSG: %s\n", msg.Payload())
    27  }
    28  
    29  func TestConnect(t *testing.T) {
    30  	// 获取emqx的客户端
    31  	emqxClient, _ := emqx.NewEmqxClient()
    32  
    33  	// 订阅主题
    34  	if token := emqxClient.Subscribe("testtopic/#", 0, msgHandler); token.Wait() && token.Error() != nil {
    35  		fmt.Println(token.Error())
    36  		os.Exit(1)
    37  	}
    38  
    39  	// 发布消息
    40  	token := emqxClient.Publish("testtopic/1", 0, false, "Hello World")
    41  	token.Wait()
    42  
    43  	time.Sleep(6 * time.Second)
    44  
    45  	// 取消订阅
    46  	if token := emqxClient.Unsubscribe("testtopic/#"); token.Wait() && token.Error() != nil {
    47  		fmt.Println(token.Error())
    48  		os.Exit(1)
    49  	}
    50  
    51  	// 断开连接
    52  	emqxClient.Disconnect(250)
    53  	time.Sleep(1 * time.Second)
    54  }