Skip to content

Instantly share code, notes, and snippets.

@FZambia
Created April 2, 2017 14:20
Show Gist options
  • Select an option

  • Save FZambia/aaa2d1e2d30472681104fce17a46a5db to your computer and use it in GitHub Desktop.

Select an option

Save FZambia/aaa2d1e2d30472681104fce17a46a5db to your computer and use it in GitHub Desktop.
Create many compression connections
package main
// Subscribe many clients, publish into channel, wait for all messages received.
// Supposed to run for channel which only have `publish` option enabled.
import (
//"encoding/json"
"log"
"strconv"
"sync"
//"sync/atomic"
"time"
"github.com/centrifugal/centrifuge-mobile"
"github.com/centrifugal/centrifugo/libcentrifugo/auth"
)
// In production you need to receive credentials from application backend.
func credentials(n int) *centrifuge.Credentials {
// Never show secret to client of your application. Keep it on your application backend only.
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)
return &centrifuge.Credentials{
User: user,
Timestamp: timestamp,
Info: info,
Token: token,
}
}
func newConnection(n int) *centrifuge.Client {
creds := credentials(n)
wsURL := "ws://localhost:8000/connection/websocket"
conf := centrifuge.DefaultConfig()
conf.WebsocketCompression = true
c := centrifuge.New(wsURL, creds, nil, conf)
err := c.Connect()
if err != nil {
log.Fatalln(err)
}
return c
}
type subEventHandler struct {
}
func (h *subEventHandler) OnMessage(sub *centrifuge.Sub, msg *centrifuge.Message) {
}
func main() {
var wg sync.WaitGroup
numSubscribers := 1000
wg.Add(numSubscribers)
for i := 0; i < numSubscribers; i++ {
time.Sleep(time.Millisecond * 100)
go func(n int) {
c := newConnection(n)
events := centrifuge.NewSubEventHandler()
events.OnMessage(&subEventHandler{})
c.Subscribe("test", events)
wg.Done()
}(i)
}
wg.Wait()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment