@@ -33,7 +33,7 @@ type Conn struct {
3333func newConn (cli * Client , queue chan * chWrite ) * Conn {
3434 c := & Conn {}
3535 c .cli = cli
36- c .state .Store (def .ConnClosed )
36+ c .state .Store (def .ConnHanged )
3737 c .pending = newPending ()
3838 c .orderlyQueue = make (chan * chWrite , 4096 )
3939 c .disorderlyQueue = queue
@@ -97,30 +97,26 @@ func (c *Conn) send(ch *chWrite, isOrderly ...bool) error {
9797}
9898
9999// 处理连接
100- func (c * Conn ) process (conn net.Conn ) ( err error ) {
100+ func (c * Conn ) process (conn net.Conn ) error {
101101 c .ctx , c .cancel = context .WithCancel (context .Background ())
102102 c .state .Store (def .ConnOpened )
103103 c .lastHeartbeatTime .Store (xtime .Now ().Unix ())
104104
105105 go c .read (conn )
106106
107- defer func () {
108- if err != nil {
109- c .close ()
110- }
111- }()
112-
113- if err = c .handshake (conn ); err != nil {
114- return
115- }
107+ if err := c .handshake (conn ); err != nil {
108+ c .close ()
116109
117- go c .write (conn )
110+ return err
111+ } else {
112+ go c .write (conn )
118113
119- return
114+ return nil
115+ }
120116}
121117
122118// 握手
123- func (c * Conn ) handshake (conn net.Conn ) ( err error ) {
119+ func (c * Conn ) handshake (conn net.Conn ) error {
124120 var (
125121 seq = uint64 (1 )
126122 call = make (chan []byte )
@@ -131,15 +127,22 @@ func (c *Conn) handshake(conn net.Conn) (err error) {
131127
132128 c .pending .store (seq , call )
133129
134- if _ , err = conn .Write (buf .Bytes ()); err != nil {
130+ defer close (call )
131+
132+ if _ , err := conn .Write (buf .Bytes ()); err != nil {
135133 c .pending .delete (seq )
136- } else {
137- <- call
134+ return err
138135 }
139136
140- close (call )
137+ ctx , cancel := context .WithTimeout (context .Background (), defaultTimeout )
138+ defer cancel ()
141139
142- return
140+ select {
141+ case <- ctx .Done ():
142+ return ctx .Err ()
143+ case <- call :
144+ return nil
145+ }
143146}
144147
145148// 读取数据
@@ -188,6 +191,7 @@ func (c *Conn) write(conn net.Conn) {
188191 deadline := t .Add (- 2 * def .HeartbeatInterval ).Unix ()
189192
190193 if c .lastHeartbeatTime .Load () < deadline {
194+ log .Warn ("connection heartbeat timeout" )
191195 c .retry (conn )
192196 return
193197 } else {
@@ -246,7 +250,7 @@ func (c *Conn) retry(conn net.Conn) {
246250 return
247251 }
248252
249- conn .Close ()
253+ _ = conn .Close ()
250254
251255 if c .cancel != nil {
252256 c .cancel ()
@@ -259,7 +263,9 @@ func (c *Conn) retry(conn net.Conn) {
259263
260264// 关闭连接
261265func (c * Conn ) close () {
262- c .state .Store (def .ConnClosed )
266+ if c .state .Swap (def .ConnClosed ) == def .ConnClosed {
267+ return
268+ }
263269
264270 c .cli .done ()
265271
0 commit comments