|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "time" |
| 10 | + |
| 11 | + kitlog "github.com/go-kit/log" |
| 12 | + "github.com/philippseith/signalr" |
| 13 | + "github.com/philippseith/signalr/chatsample/middleware" |
| 14 | + "github.com/philippseith/signalr/chatsample/public" |
| 15 | +) |
| 16 | + |
| 17 | +// chatPerConnection is a hub that maintains state per connection |
| 18 | +type chatPerConnection struct { |
| 19 | + signalr.Hub |
| 20 | + connectionID string |
| 21 | + username string |
| 22 | + messageCount int |
| 23 | + joinTime time.Time |
| 24 | +} |
| 25 | + |
| 26 | +func (c *chatPerConnection) OnConnected(connectionID string) { |
| 27 | + c.connectionID = connectionID |
| 28 | + c.messageCount = 0 |
| 29 | + c.joinTime = time.Now() |
| 30 | + c.username = fmt.Sprintf("User_%s", connectionID[:8]) // Generate username from connection ID |
| 31 | + |
| 32 | + fmt.Printf("New connection: %s, Username: %s\n", connectionID, c.username) |
| 33 | + |
| 34 | + // Send welcome message to the new user |
| 35 | + c.Clients().Caller().Send("ReceiveMessage", "System", fmt.Sprintf("Welcome %s! You are connection #%s", c.username, connectionID[:8])) |
| 36 | + |
| 37 | + // Broadcast to all clients that a new user joined |
| 38 | + c.Clients().All().Send("ReceiveMessage", "System", fmt.Sprintf("%s has joined the chat", c.username)) |
| 39 | +} |
| 40 | + |
| 41 | +func (c *chatPerConnection) OnDisconnected(connectionID string) { |
| 42 | + fmt.Printf("Connection closed: %s, Username: %s, Messages sent: %d, Duration: %v\n", |
| 43 | + connectionID, c.username, c.messageCount, time.Since(c.joinTime)) |
| 44 | + |
| 45 | + // Broadcast to all clients that a user left |
| 46 | + c.Clients().All().Send("ReceiveMessage", "System", fmt.Sprintf("%s has left the chat", c.username)) |
| 47 | +} |
| 48 | + |
| 49 | +func (c *chatPerConnection) SendMessage(message string) { |
| 50 | + c.messageCount++ |
| 51 | + |
| 52 | + // Log the message with connection-specific info |
| 53 | + fmt.Printf("[%s] %s: %s (Message #%d)\n", c.connectionID[:8], c.username, message, c.messageCount) |
| 54 | + |
| 55 | + // Send message to all clients |
| 56 | + c.Clients().All().Send("ReceiveMessage", c.username, message) |
| 57 | +} |
| 58 | + |
| 59 | +func (c *chatPerConnection) SetUsername(username string) { |
| 60 | + oldUsername := c.username |
| 61 | + c.username = username |
| 62 | + |
| 63 | + fmt.Printf("Username changed: %s -> %s (Connection: %s)\n", oldUsername, username, c.connectionID[:8]) |
| 64 | + |
| 65 | + // Broadcast username change |
| 66 | + c.Clients().All().Send("ReceiveMessage", "System", fmt.Sprintf("%s is now known as %s", oldUsername, username)) |
| 67 | +} |
| 68 | + |
| 69 | +func (c *chatPerConnection) GetStats() map[string]interface{} { |
| 70 | + return map[string]interface{}{ |
| 71 | + "connectionID": c.connectionID[:8], |
| 72 | + "username": c.username, |
| 73 | + "messageCount": c.messageCount, |
| 74 | + "joinTime": c.joinTime.Format(time.RFC3339), |
| 75 | + "duration": time.Since(c.joinTime).String(), |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +func (c *chatPerConnection) Echo(message string) { |
| 80 | + c.Clients().Caller().Send("ReceiveMessage", "Echo", message) |
| 81 | +} |
| 82 | + |
| 83 | +func (c *chatPerConnection) Abort() { |
| 84 | + fmt.Printf("Aborting connection: %s, Username: %s\n", c.connectionID[:8], c.username) |
| 85 | + c.Hub.Abort() |
| 86 | +} |
| 87 | + |
| 88 | +func runHTTPServerPerConnection(address string) { |
| 89 | + // Create server with PerConnectionHubFactory |
| 90 | + server, _ := signalr.NewServer(context.TODO(), |
| 91 | + signalr.PerConnectionHubFactory(func(connectionID string) signalr.HubInterface { |
| 92 | + return &chatPerConnection{} |
| 93 | + }), |
| 94 | + signalr.Logger(kitlog.NewLogfmtLogger(os.Stdout), false), |
| 95 | + signalr.KeepAliveInterval(2*time.Second)) |
| 96 | + |
| 97 | + router := http.NewServeMux() |
| 98 | + server.MapHTTP(signalr.WithHTTPServeMux(router), "/chat") |
| 99 | + |
| 100 | + fmt.Printf("Serving public content from the embedded filesystem\n") |
| 101 | + router.Handle("/", http.FileServer(http.FS(public.FS))) |
| 102 | + fmt.Printf("Listening for websocket connections on http://%s\n", address) |
| 103 | + fmt.Printf("Using PerConnectionHubFactory - each connection gets its own hub instance!\n") |
| 104 | + |
| 105 | + if err := http.ListenAndServe(address, middleware.LogRequests(router)); err != nil { |
| 106 | + log.Fatal("ListenAndServe:", err) |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +func runHTTPClientPerConnection(address string, receiver interface{}) error { |
| 111 | + c, err := signalr.NewClient(context.Background(), nil, |
| 112 | + signalr.WithReceiver(receiver), |
| 113 | + signalr.WithConnector(func() (signalr.Connection, error) { |
| 114 | + creationCtx, _ := context.WithTimeout(context.Background(), 2*time.Second) |
| 115 | + return signalr.NewHTTPConnection(creationCtx, address) |
| 116 | + }), |
| 117 | + signalr.Logger(kitlog.NewLogfmtLogger(os.Stdout), false)) |
| 118 | + if err != nil { |
| 119 | + return err |
| 120 | + } |
| 121 | + c.Start() |
| 122 | + fmt.Println("Client started") |
| 123 | + return nil |
| 124 | +} |
| 125 | + |
| 126 | +type receiverPerConnection struct { |
| 127 | + signalr.Receiver |
| 128 | +} |
| 129 | + |
| 130 | +func (r *receiverPerConnection) Receive(msg string) { |
| 131 | + fmt.Println(msg) |
| 132 | + // The silly client urges the server to end his connection after 10 seconds |
| 133 | + r.Server().Send("abort") |
| 134 | +} |
| 135 | + |
| 136 | +func mainPerConnection() { |
| 137 | + fmt.Println("=== Per-Connection Hub Factory Demo ===") |
| 138 | + fmt.Println("This demo shows how each connection gets its own hub instance") |
| 139 | + fmt.Println("with persistent state throughout the connection lifetime.") |
| 140 | + fmt.Println() |
| 141 | + |
| 142 | + go runHTTPServerPerConnection("localhost:8087") |
| 143 | + <-time.After(time.Millisecond * 2) |
| 144 | + |
| 145 | + go func() { |
| 146 | + fmt.Println(runHTTPClientPerConnection("http://localhost:8087/chat", &receiverPerConnection{})) |
| 147 | + }() |
| 148 | + |
| 149 | + ch := make(chan struct{}) |
| 150 | + <-ch |
| 151 | +} |
0 commit comments