示例#1
0
文件: main.go 项目: pubnub/go
func subscribe(w http.ResponseWriter, r *http.Request) {
	var errorChannel = make(chan []byte)
	var subscribeChannel = make(chan []byte)
	messaging.LoggingEnabled(true)
	messaging.SetLogOutput(os.Stdout)
	pubInstance := messaging.NewPubnub(publishKey, subscribeKey, secretKey, "", true, "")

	go pubInstance.Subscribe("test2", "", subscribeChannel, false, errorChannel)
	go handleSubscribeResult(subscribeChannel, errorChannel, "Subscribe")
}
示例#2
0
func TestWildcardSubscriptionMessage(t *testing.T) {
	assert := assert.New(t)

	stop, _ := NewVCRBoth("fixtures/wildcard/message", []string{"uuid"})
	defer stop()

	uuid := "UUID_SubscribeMajor"
	major := "Channel_SubscribeMajor"
	minor := "Channel_SubscribeMinor"
	channel := fmt.Sprintf("%s.%s", major, minor)
	wildcard := fmt.Sprintf("%s.*", major)
	messaging.SetLogOutput(os.Stdout)
	//messaging.LoggingEnabled(true)

	pubnubInstance := messaging.NewPubnub(PubKey, SubKey, "", "", false, uuid)

	subscribeSuccessChannel := make(chan []byte)
	subscribeErrorChannel := make(chan []byte)
	successChannel := make(chan []byte)
	errorChannel := make(chan []byte)

	await := make(chan bool)

	go pubnubInstance.Subscribe(wildcard, "",
		subscribeSuccessChannel, false, subscribeErrorChannel)

	ExpectConnectedEvent(t, wildcard, "", subscribeSuccessChannel,
		subscribeErrorChannel)

	go func() {
		select {
		case message := <-subscribeSuccessChannel:
			var msg []interface{}

			err := json.Unmarshal(message, &msg)
			if err != nil {
				assert.Fail(err.Error())
			}

			assert.Contains(string(message), "hey")
			assert.Equal(channel, msg[2].(string))
			assert.Equal(wildcard, msg[3].(string))
			await <- true
		case err := <-subscribeErrorChannel:
			assert.Fail(string(err))
			await <- false
		case <-messaging.SubscribeTimeout():
			assert.Fail("Subscribe timeout")
			await <- false
		}
	}()

	go pubnubInstance.Publish(channel, "hey", successChannel, errorChannel)
	select {
	case <-successChannel:
	case err := <-errorChannel:
		assert.Fail(string(err))
	}

	<-await

	go pubnubInstance.Unsubscribe(wildcard, successChannel, errorChannel)
	ExpectUnsubscribedEvent(t, wildcard, "", successChannel, errorChannel)

	// pubnubInstance.CloseExistingConnection()
}
示例#3
0
// Init asks the user the basic settings to initialize to the pubnub struct.
// Settings include the pubnub channel(s) to connect to.
// Ssl settings
// Cipher key
// Secret Key
// Custom Uuid
// Proxy details
//
// The method returns false if the channel name is not provided.
//
// returns: a bool, true if the user completed the initail settings.
func Init() (b bool) {
	fmt.Println("")
	fmt.Println(messaging.VersionInfo())
	messaging.SetMaxIdleConnsPerHost(20)
	fmt.Println("")
	fmt.Println("Please enter the channel name(s). Enter multiple channels separated by comma without spaces.")
	reader := bufio.NewReader(os.Stdin)

	line, _, err := reader.ReadLine()
	if err != nil {
		fmt.Println(err)
	} else {
		connectChannels = string(line)
		if strings.TrimSpace(connectChannels) != "" {
			fmt.Println("Channel: ", connectChannels)
			fmt.Println("Enable SSL? Enter y for Yes, n for No.")
			var enableSsl string
			fmt.Scanln(&enableSsl)

			if enableSsl == "y" || enableSsl == "Y" {
				ssl = true
				fmt.Println("SSL enabled")
			} else {
				ssl = false
				fmt.Println("SSL disabled")
			}

			fmt.Println("Please enter a subscribe key, leave blank for default key.")
			fmt.Scanln(&subscribeKey)

			if strings.TrimSpace(subscribeKey) == "" {
				subscribeKey = "demo"
			}
			fmt.Println("Subscribe Key: ", subscribeKey)
			fmt.Println("")

			fmt.Println("Please enter a publish key, leave blank for default key.")
			fmt.Scanln(&publishKey)
			if strings.TrimSpace(publishKey) == "" {
				publishKey = "demo"
			}
			fmt.Println("Publish Key: ", publishKey)
			fmt.Println("")

			fmt.Println("Please enter a secret key, leave blank for default key.")
			fmt.Scanln(&secretKey)
			if strings.TrimSpace(secretKey) == "" {
				secretKey = "demo"
			}
			fmt.Println("Secret Key: ", secretKey)
			fmt.Println("")

			fmt.Println("Please enter a CIPHER key, leave blank if you don't want to use this.")
			fmt.Scanln(&cipher)
			fmt.Println("Cipher: ", cipher)

			fmt.Println("Please enter a Custom UUID, leave blank for default.")
			fmt.Scanln(&uuid)
			fmt.Println("UUID: ", uuid)

			fmt.Println("Display error messages? Enter y for Yes, n for No. Default is Yes")
			var enableErrorMessages = "y"
			fmt.Scanln(&enableErrorMessages)

			if enableErrorMessages == "y" || enableErrorMessages == "Y" {
				displayError = true
				fmt.Println("Error messages will be displayed")
			} else {
				displayError = false
				fmt.Println("Error messages will not be displayed")
			}

			fmt.Println("Enable resume on reconnect? Enter y for Yes, n for No. Default is Yes")
			var enableResumeOnReconnect = "y"
			fmt.Scanln(&enableResumeOnReconnect)

			if enableResumeOnReconnect == "y" || enableResumeOnReconnect == "Y" {
				messaging.SetResumeOnReconnect(true)
				fmt.Println("Resume on reconnect enabled")
			} else {
				messaging.SetResumeOnReconnect(false)
				fmt.Println("Resume on reconnect disabled")
			}

			fmt.Println("Set subscribe timeout? Enter numerals.")
			var subscribeTimeout = ""
			fmt.Scanln(&subscribeTimeout)
			val, err := strconv.Atoi(subscribeTimeout)
			if err != nil {
				fmt.Println("Entered value is invalid. Using default value.")
			} else {
				messaging.SetSubscribeTimeout(uint16(val))
			}

			fmt.Println("Enable logging? Enter y for Yes, n for No. Default is Yes")
			var enableLogging = "y"
			fmt.Scanln(&enableLogging)

			if enableLogging == "y" || enableLogging == "Y" {
				messaging.LoggingEnabled(true)
				logfileName := "pubnubMessaging.log"
				f, err := os.OpenFile(logfileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
				if err != nil {
					fmt.Println("error opening file: ", err.Error())
					fmt.Println("Logging disabled")
				} else {
					fmt.Println("Logging enabled writing to ", logfileName)
					messaging.SetLogOutput(f)
				}
			} else {
				messaging.SetResumeOnReconnect(false)
				fmt.Println("Logging disabled")
			}

			messaging.SetOrigin("pubsub.pubnub.com")

			var pubInstance = messaging.NewPubnub(publishKey, subscribeKey, secretKey, cipher, ssl, uuid)
			pub = pubInstance

			SetupProxy()

			presenceHeartbeat := askNumber16("Presence Heartbeat", true)
			pub.SetPresenceHeartbeat(presenceHeartbeat)
			fmt.Println(fmt.Sprintf("Presence Heartbeat set to :%d", pub.GetPresenceHeartbeat()))

			presenceHeartbeatInterval := askNumber16("Presence Heartbeat Interval", true)
			pub.SetPresenceHeartbeat(presenceHeartbeatInterval)
			fmt.Println(fmt.Sprintf("Presence Heartbeat set to :%d", pub.GetPresenceHeartbeat()))

			fmt.Println("Pubnub instance initialized")

			return true
		}
		fmt.Println("Channel cannot be empty.")
	}
	return false
}