func serverHandleConnection(s *Server, conn io.ReadWriteCloser, clientAddr string, workersCh chan struct{}) {
defer s.stopWg.Done()
if s.OnConnect != nil {
newConn, err := s.OnConnect(clientAddr, conn)
if err != nil {
s.LogError("gorpc.Server: [%s]->[%s]. OnConnect error: [%s]", clientAddr, s.Addr, err)
conn.Close()
return
}
conn = newConn
}
var enabledCompression bool
var err error
var stopping atomic.Value
zChan := make(chan bool, 1)
go func() {
var buf [1]byte
if _, err = conn.Read(buf[:]); err != nil {
if stopping.Load() == nil {
s.LogError("gorpc.Server: [%s]->[%s]. Error when reading handshake from client: [%s]", clientAddr, s.Addr, err)
}
}
zChan <- (buf[0] != 0)
}()
select {
case enabledCompression = <-zChan: // 第一個(gè)標(biāo)志位 代表被壓縮
if err != nil {
conn.Close()
return
}
case <-s.serverStopChan:
stopping.Store(true)
conn.Close()
return
case <-time.After(10 * time.Second):
s.LogError("gorpc.Server: [%s]->[%s]. Cannot obtain handshake from client during 10s", clientAddr, s.Addr)
conn.Close()
return
}
responsesChan := make(chan *serverMessage, s.PendingResponses)
stopChan := make(chan struct{})
readerDone := make(chan struct{})
go serverReader(s, conn, clientAddr, responsesChan, stopChan, readerDone, enabledCompression, workersCh)
writerDone := make(chan struct{})
go serverWriter(s, conn, clientAddr, responsesChan, stopChan, writerDone, enabledCompression)
select {
case <-readerDone:
close(stopChan)
conn.Close()
<-writerDone
case <-writerDone:
close(stopChan)
conn.Close()
<-readerDone
case <-s.serverStopChan:
close(stopChan)
conn.Close()
<-readerDone
<-writerDone
}
}
- OnConnect,像中間件一樣對(duì)原本的clientAddr和conn進(jìn)行處理弓熏,可以記錄日志,甚至可以封裝糠睡。
- zChan用于通知消息是否被壓縮挽鞠。
- 啟動(dòng)讀協(xié)程和寫協(xié)程去讀取消息。讀寫協(xié)程之間的交互靠responsesChan狈孔,停止靠stopCh通信同時(shí)通知兩個(gè)協(xié)程信认。
- 調(diào)用函數(shù)被 讀寫協(xié)程readDone和writerDone通知,如果讀寫協(xié)程崩潰則通知調(diào)用函數(shù)均抽。進(jìn)而同時(shí)通知stopChan關(guān)閉另一個(gè)
- 如果serverStopChan(上層停止調(diào)用)通知狮杨,則直接close(stopChan)通知讀寫協(xié)程退出。
寫的很巧妙到忽,像詩(shī)一樣