Skip to content

Commit 4d9857b

Browse files
committed
Use state machine to refactor czar client
1 parent 718f107 commit 4d9857b

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

protocol/czar/engine.go

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,13 @@ func (c *Client) Dial(ctx *daze.Context, network string, address string) (io.Rea
147147

148148
// Run creates an establish connection to czar server.
149149
func (c *Client) Run() {
150+
const (
151+
clientStatusClosed int = iota
152+
clientStatusDialFailure
153+
clientStatusDialSuccess
154+
clientStatusEstablished
155+
clientStatusCancel
156+
)
150157
var (
151158
err error
152159
mux *Mux
@@ -156,40 +163,41 @@ func (c *Client) Run() {
156163
)
157164
for {
158165
switch sid {
159-
case 0:
160-
sid = 2
166+
case clientStatusClosed:
161167
srv, err = daze.Dial("tcp", c.Server)
162168
if err != nil {
163-
sid = 1
169+
sid = clientStatusDialFailure
170+
} else {
171+
sid = clientStatusDialSuccess
164172
}
165-
case 1:
173+
case clientStatusDialFailure:
166174
log.Println("czar:", err)
167175
select {
168176
case <-time.After(time.Second * time.Duration(math.Pow(2, float64(rtt)))):
169177
// A slow start reconnection algorithm.
170178
rtt = min(rtt+1, 5)
171-
sid = 0
179+
sid = clientStatusClosed
172180
case <-c.Cancel:
173-
sid = 4
181+
sid = clientStatusCancel
174182
}
175-
case 2:
183+
case clientStatusDialSuccess:
176184
log.Println("czar: mux init")
177185
mux = NewMuxClient(srv)
178186
rtt = 0
179-
sid = 3
180-
case 3:
187+
sid = clientStatusEstablished
188+
case clientStatusEstablished:
181189
select {
182190
case c.Mux <- mux:
183191
case <-mux.rer.Sig():
184192
log.Println("czar: mux done")
185193
mux.Close()
186-
sid = 0
194+
sid = clientStatusClosed
187195
case <-c.Cancel:
188196
log.Println("czar: mux done")
189197
mux.Close()
190-
sid = 4
198+
sid = clientStatusCancel
191199
}
192-
case 4:
200+
case clientStatusCancel:
193201
return
194202
}
195203
}

0 commit comments

Comments
 (0)