func main() {

	origin := "http://localhost:8000/"
	url := os.Args[1]
	secret := os.Args[2]
	clients, _ := strconv.Atoi(os.Args[3])

	fmt.Printf("clients: %d\n", clients)

	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	token := auth.GenerateClientToken(secret, "test", timestamp, "")
	connectMessage := fmt.Sprintf("{\"params\": {\"timestamp\": \"%s\", \"token\": \"%s\", \"user\": \"test\"}, \"method\": \"connect\"}", timestamp, token)
	subscribeMessage := "{\"params\": {\"channel\": \"test\"}, \"method\": \"subscribe\"}"
	done := make(chan struct{})

	for i := 0; i < clients; i += 1 {
		chSub := make(chan struct{})
		go subscriber(chSub, url, origin, connectMessage, subscribeMessage)
		<-chSub
		fmt.Printf("\r%d", i+1)
	}

	// Just run until interrupted keeping connections open.
	<-done
}
Exemple #2
0
func NewClient(num int, wg *sync.WaitGroup, done chan bool) *Client {
	user := strconv.Itoa(num)
	timestamp := centrifuge.Timestamp()
	token := auth.GenerateClientToken(*secret, user, timestamp, "")

	client := &Client{wg: wg, done: done}

	creds := &centrifuge.Credentials{
		User:      user,
		Timestamp: timestamp,
		Info:      "",
		Token:     token,
	}

	events := &centrifuge.EventHandler{
		OnDisconnect: client.DisconnectHandler,
		OnPrivateSub: nil,
		OnRefresh:    nil,
	}

	cent := centrifuge.NewCentrifuge(wsUrl, creds, events, centrifuge.DefaultConfig)

	delay := time.Duration(*msgDelay) * time.Millisecond

	client.creds = creds
	client.cent = cent
	client.delay = delay

	return client
}
func newConnection(n int) centrifuge.Centrifuge {
	secret := "secret"

	// Application user ID.
	user := strconv.Itoa(n)

	// Current timestamp as string.
	timestamp := centrifuge.Timestamp()

	// Empty info.
	info := ""

	// Generate client token so Centrifugo server can trust connection parameters received from client.
	token := auth.GenerateClientToken(secret, user, timestamp, info)

	creds := &centrifuge.Credentials{
		User:      user,
		Timestamp: timestamp,
		Info:      info,
		Token:     token,
	}

	wsURL := "ws://localhost:8000/connection/websocket"
	c := centrifuge.NewCentrifuge(wsURL, creds, nil, centrifuge.DefaultConfig)

	err := c.Connect()
	if err != nil {
		log.Fatalln(err)
	}
	return c
}
Exemple #4
0
func testRefreshCmd(timestamp string) clientCommand {
	token := auth.GenerateClientToken("secret", "user1", timestamp, "")
	refreshCmd := RefreshClientCommand{
		Timestamp: timestamp,
		User:      UserID("user1"),
		Info:      "",
		Token:     token,
	}
	cmdBytes, _ := json.Marshal(refreshCmd)
	cmd := clientCommand{
		Method: "refresh",
		Params: cmdBytes,
	}
	return cmd
}
Exemple #5
0
func testConnectCmd(timestamp string) clientCommand {
	token := auth.GenerateClientToken("secret", "test1", "user1", timestamp, "")
	connectCmd := connectClientCommand{
		Project:   ProjectKey("test1"),
		Timestamp: timestamp,
		User:      UserID("user1"),
		Info:      "",
		Token:     token,
	}
	cmdBytes, _ := json.Marshal(connectCmd)
	cmd := clientCommand{
		Method: "connect",
		Params: cmdBytes,
	}
	return cmd
}
func credentials() *centrifuge.Credentials {
	secret := "secret"

	// Application user ID.
	user := "******"

	// Current timestamp as string.
	timestamp := centrifuge.Timestamp()

	// Empty info.
	info := ""

	// Generate client token so Centrifugo server can trust connection parameters received from client.
	token := auth.GenerateClientToken(secret, user, timestamp, info)

	return &centrifuge.Credentials{
		User:      user,
		Timestamp: timestamp,
		Info:      info,
		Token:     token,
	}
}
Exemple #7
0
func main() {

	origin := "http://localhost:8000/"
	url := os.Args[1]
	secret := os.Args[2]
	maxClients, _ := strconv.Atoi(os.Args[3])
	increment, _ := strconv.Atoi(os.Args[4])
	repeats, _ := strconv.Atoi(os.Args[5])

	fmt.Printf("max clients: %d\n", maxClients)
	fmt.Printf("increment: %d\n", increment)
	fmt.Printf("repeat: %d\n", repeats)

	messagesReceived := 0

	timestamp := strconv.FormatInt(time.Now().Unix(), 10)

	token := auth.GenerateClientToken(secret, "test", timestamp, "")

	connectMessage := fmt.Sprintf("{\"params\": {\"timestamp\": \"%s\", \"token\": \"%s\", \"user\": \"test\"}, \"method\": \"connect\"}", timestamp, token)
	subscribeMessage := "{\"params\": {\"channel\": \"test\"}, \"method\": \"subscribe\"}"
	publishMessage := "{\"params\": {\"data\": {\"input\": \"I am benchmarking Centrifuge at moment\"}, \"channel\": \"test\"}, \"method\": \"publish\"}"

	chSub := make(chan int)
	chMsg := make(chan int)
	chStart := make(chan int)
	chTrigger := make(chan int)
	chTime := make(chan time.Time)

	var startTime time.Time

	totalTime := 0.0

	fullTime := 0.0

	go func() {
		publisher(chTrigger, chTime, url, origin, connectMessage, subscribeMessage, publishMessage)
	}()

	for i := 0; i < maxClients; i += increment {

		time.Sleep(50 * time.Millisecond)
		totalTime = 0
		for j := 0; j < increment; j++ {
			time.Sleep(5 * time.Millisecond)
			go func() {
				subscriber(chSub, chMsg, chStart, url, origin, connectMessage, subscribeMessage, publishMessage)
			}()
			<-chSub

		}

		currentClients := i + increment

		// repeat several times to get average time value
		for k := 0; k < repeats; k++ {
			time.Sleep(100 * time.Millisecond)
			fullTime = 0.0
			messagesReceived = 0
			// publish message
			chTrigger <- 1
			startTime = <-chTime
			for {
				<-chMsg
				messagesReceived += 1
				elapsed := time.Since(startTime)
				fullTime += float64(elapsed)
				if messagesReceived == currentClients {
					break
				}
			}
			totalTime += fullTime / float64(currentClients)
		}
		fmt.Printf("%d\t%d\n", currentClients, int(totalTime/float64(repeats)))
	}
}
Exemple #8
0
func main() {
	// Never show secret to client of your application. Keep it on your application backend only.
	secret := "secret"

	// Application user ID.
	user := "******"

	// Current timestamp as string.
	timestamp := centrifuge.Timestamp()

	// Empty info.
	info := ""

	// Generate client token so Centrifugo server can trust connection parameters received from client.
	token := auth.GenerateClientToken(secret, user, timestamp, info)

	creds := &centrifuge.Credentials{
		User:      user,
		Timestamp: timestamp,
		Info:      info,
		Token:     token,
	}

	started := time.Now()

	wsURL := "ws://localhost:8000/connection/websocket"
	c := centrifuge.NewCentrifuge(wsURL, creds, nil, centrifuge.DefaultConfig)
	defer c.Close()

	err := c.Connect()
	if err != nil {
		log.Fatalln(err)
	}

	onMessage := func(sub centrifuge.Sub, msg centrifuge.Message) error {
		log.Println(fmt.Sprintf("New message received in channel %s: %#v", sub.Channel(), msg))
		return nil
	}

	onJoin := func(sub centrifuge.Sub, msg centrifuge.ClientInfo) error {
		log.Println(fmt.Sprintf("User %s joined channel %s with client ID %s", msg.User, sub.Channel(), msg.Client))
		return nil
	}

	onLeave := func(sub centrifuge.Sub, msg centrifuge.ClientInfo) error {
		log.Println(fmt.Sprintf("User %s with clientID left channel %s with client ID %s", msg.User, msg.Client, sub.Channel()))
		return nil
	}

	events := &centrifuge.SubEventHandler{
		OnMessage: onMessage,
		OnJoin:    onJoin,
		OnLeave:   onLeave,
	}

	sub, err := c.Subscribe("public:chat", events)
	if err != nil {
		log.Fatalln(err)
	}

	data := map[string]string{
		"input": "test",
	}
	dataBytes, _ := json.Marshal(data)
	err = sub.Publish(dataBytes)
	if err != nil {
		log.Fatalln(err)
	}

	history, err := sub.History()
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("%d messages in channel %s history", len(history), sub.Channel())

	presence, err := sub.Presence()
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("%d clients in channel %s", len(presence), sub.Channel())

	err = sub.Unsubscribe()
	if err != nil {
		log.Fatalln(err)
	}

	log.Printf("%s", time.Since(started))

}