Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
61 lines (53 loc) · 1.48 KB
/
Copy pathserver.go
File metadata and controls
61 lines (53 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package netcode
import (
"sync"
"github.com/rfwlab/rfw/v2/host"
)
// Server applies commands and broadcasts state snapshots.
type Server[T any] struct {
name string
state T
apply func(*T, any)
mu sync.Mutex
}
// NewServer creates a Server for the given component name and initial state.
func NewServer[T any](name string, initial T, apply func(*T, any)) *Server[T] {
return &Server[T]{name: name, state: initial, apply: apply}
}
// HostComponent returns the handler to register with host.Register.
func (s *Server[T]) HostComponent() *host.HostComponent {
return host.NewHostComponent(s.name, func(payload map[string]any) any {
if cmds, ok := payload["commands"].([]any); ok {
s.mu.Lock()
for _, cmd := range cmds {
s.apply(&s.state, cmd)
}
s.mu.Unlock()
}
return nil
})
}
// Snapshot returns the current state.
func (s *Server[T]) Snapshot() T {
s.mu.Lock()
defer s.mu.Unlock()
return s.state
}
// Broadcast pushes the current state with tick to all clients.
func (s *Server[T]) Broadcast(tick int64) {
s.mu.Lock()
state := s.state
s.mu.Unlock()
host.Broadcast(s.name, map[string]any{"tick": tick, "state": state})
}
// Update acquires the server lock and invokes fn with the current state.
// It can be used to apply deterministic updates outside of command handlers,
// such as running fixed-step simulation loops before broadcasting snapshots.
func (s *Server[T]) Update(fn func(*T)) {
if fn == nil {
return
}
s.mu.Lock()
fn(&s.state)
s.mu.Unlock()
}