-
-
Notifications
You must be signed in to change notification settings - Fork 93
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
16 changed files
with
579 additions
and
82 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="utf-8"> | ||
<title></title> | ||
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> | ||
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script> | ||
<script type="text/javascript" src="//cdn.jsdelivr.net/gh/centrifugal/centrifuge-js@latest/dist/centrifuge.min.js"></script> | ||
<script type="text/javascript"> | ||
$(function () { | ||
const container = $('#messages'); | ||
|
||
const centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket'); | ||
// var centrifuge = new Centrifuge('http://localhost:8000/connection/sockjs', { | ||
// sockjsTransports: [ | ||
// "xhr-streaming", | ||
// ] | ||
// }); | ||
|
||
// bind listeners on centrifuge object instance events. | ||
centrifuge.on('connect', function(ctx){ | ||
drawText('Connected with client ID ' + ctx.client + ' over ' + ctx.transport); | ||
}); | ||
|
||
centrifuge.on('disconnect', function(ctx){ | ||
drawText('Disconnected: ' + ctx.reason + (ctx.reconnect?", will try to reconnect":", won't try to reconnect")); | ||
}); | ||
|
||
// Trigger actual connection establishing with a server. | ||
// At this moment actual client work starts - i.e. subscriptions | ||
// defined start subscribing etc. | ||
centrifuge.connect(); | ||
|
||
function drawText(text) { | ||
container.prepend($('<li/>').html([(new Date()).toString(), ' ' + text].join(':'))); | ||
} | ||
}); | ||
</script> | ||
</head> | ||
<body> | ||
<ul id="messages"></ul> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"log" | ||
"net/http" | ||
"os" | ||
"os/signal" | ||
"syscall" | ||
|
||
_ "net/http/pprof" | ||
|
||
"github.com/centrifugal/centrifuge" | ||
) | ||
|
||
func handleLog(e centrifuge.LogEntry) { | ||
log.Printf("%s: %v", e.Message, e.Fields) | ||
} | ||
|
||
func authMiddleware(h http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
ctx := r.Context() | ||
newCtx := centrifuge.SetCredentials(ctx, ¢rifuge.Credentials{ | ||
UserID: "42", | ||
Info: []byte(`{"name": "Alexander"}`), | ||
}) | ||
r = r.WithContext(newCtx) | ||
h.ServeHTTP(w, r) | ||
}) | ||
} | ||
|
||
func waitExitSignal(n *centrifuge.Node) { | ||
sigCh := make(chan os.Signal, 1) | ||
done := make(chan bool, 1) | ||
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) | ||
go func() { | ||
<-sigCh | ||
_ = n.Shutdown(context.Background()) | ||
done <- true | ||
}() | ||
<-done | ||
} | ||
|
||
func main() { | ||
cfg := centrifuge.DefaultConfig | ||
cfg.LogLevel = centrifuge.LogLevelInfo | ||
cfg.LogHandler = handleLog | ||
|
||
node, _ := centrifuge.New(cfg) | ||
|
||
node.OnConnecting(func(ctx context.Context, e centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) { | ||
cred, _ := centrifuge.GetCredentials(ctx) | ||
return centrifuge.ConnectReply{ | ||
// Subscribe to personal several server-side channel. | ||
Subscriptions: map[string]centrifuge.SubscribeOptions{ | ||
"#" + cred.UserID: {Presence: true}, | ||
}, | ||
}, nil | ||
}) | ||
|
||
node.OnConnect(func(client *centrifuge.Client) { | ||
presenceStats, err := node.PresenceStats("#" + client.UserID()) | ||
if err != nil { | ||
client.Disconnect(centrifuge.DisconnectServerError) | ||
return | ||
} | ||
if presenceStats.NumClients >= 2 { | ||
err = node.Disconnect( | ||
client.UserID(), | ||
centrifuge.WithDisconnect(centrifuge.DisconnectConnectionLimit), | ||
centrifuge.WithClientWhitelist([]string{client.ID()}), | ||
) | ||
if err != nil { | ||
client.Disconnect(centrifuge.DisconnectServerError) | ||
return | ||
} | ||
} | ||
|
||
transport := client.Transport() | ||
log.Printf("user %s connected via %s with protocol: %s", client.UserID(), transport.Name(), transport.Protocol()) | ||
|
||
client.OnDisconnect(func(e centrifuge.DisconnectEvent) { | ||
log.Printf("user %s disconnected, disconnect: %s", client.UserID(), e.Disconnect) | ||
}) | ||
}) | ||
|
||
if err := node.Run(); err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
websocketHandler := centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{ | ||
ReadBufferSize: 1024, | ||
UseWriteBufferPool: true, | ||
}) | ||
http.Handle("/connection/websocket", authMiddleware(websocketHandler)) | ||
|
||
sockjsHandler := centrifuge.NewSockjsHandler(node, centrifuge.SockjsConfig{ | ||
URL: "https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js", | ||
HandlerPrefix: "/connection/sockjs", | ||
WebsocketReadBufferSize: 1024, | ||
WebsocketWriteBufferSize: 1024, | ||
}) | ||
http.Handle("/connection/sockjs/", authMiddleware(sockjsHandler)) | ||
http.Handle("/", http.FileServer(http.Dir("./"))) | ||
|
||
go func() { | ||
if err := http.ListenAndServe(":8000", nil); err != nil { | ||
log.Fatal(err) | ||
} | ||
}() | ||
|
||
waitExitSignal(node) | ||
log.Println("bye!") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
This example demonstrates how to keep single connection from the same user globally over all Centrifuge nodes. | ||
|
||
As soon as user connects we subscribe it to a personal channel with presence enabled. Then inside `OnConnect` handler we check whether user has more than 1 connection inside personal channel at the moment. If yes – we disconnect other user connections (except current one) from a server. | ||
|
||
We also could disconnect all other user connections without using channel presence at all, but this results in more unnecessary disconnect messages travelling around Centrifuge nodes. | ||
|
||
To start example run the following command from example directory: | ||
|
||
``` | ||
go run main.go | ||
``` | ||
|
||
Then go to http://localhost:8000 to see it in action. Then open another browser tab – as soon as the new connection establishes the previous one will be closed. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.