Skip to content

Commit

Permalink
代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
吴迎松 committed Oct 16, 2017
1 parent 13f1592 commit afae40a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 193 deletions.
190 changes: 0 additions & 190 deletions conn.go

This file was deleted.

14 changes: 11 additions & 3 deletions tcp_conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tcp

import (
"errors"
"fmt"
"io"
"net"
"strings"
Expand All @@ -26,7 +27,6 @@ type TCPConn struct {

readDeadline time.Duration
writeDeadline time.Duration
maxPacketSize uint32

exitChan chan struct{}
closeOnce sync.Once
Expand All @@ -49,17 +49,23 @@ func NewTCPConn(conn *net.TCPConn, callback CallBack, protocol Protocol) *TCPCon
return c
}

func (c *TCPConn) Serve() {
func (c *TCPConn) Serve() error {
defer func() {
if r := recover(); r != nil {
logger.Println("tcp conn(%v) Serve error, %v ", c.GetRemoteIPAddress(), r)
}
}()
if c.callback == nil || c.protocol == nil {
err := fmt.Errorf("callback and protocol are not allowed to be nil")
c.Close()
return err
}
atomic.StoreInt32(&c.exitFlag, 1)
c.callback.OnConnected(c)
go c.readLoop()
go c.writeLoop()
go c.handleLoop()
return nil
}

func (c *TCPConn) readLoop() {
Expand Down Expand Up @@ -146,7 +152,9 @@ func (c *TCPConn) Close() {
close(c.errChan)
close(c.writeChan)
close(c.readChan)
c.callback.OnDisconnected(c)
if c.callback != nil {
c.callback.OnDisconnected(c)
}
atomic.StoreInt32(&c.exitFlag, 0)
c.conn.Close()
})
Expand Down

0 comments on commit afae40a

Please sign in to comment.