TcpService服务新增读写超时配置

This commit is contained in:
boyce
2020-12-03 15:45:13 +08:00
parent 9db4a42d10
commit dfba2fbe47
2 changed files with 32 additions and 0 deletions

View File

@@ -5,6 +5,7 @@ import (
"github.com/duanhf2012/origin/log"
"net"
"sync"
"time"
)
type ConnSet map[net.Conn]struct{}
@@ -138,3 +139,11 @@ func (tcpConn *TCPConn) WriteMsg(args ...[]byte) error {
func (tcpConn *TCPConn) IsConnected() bool {
return tcpConn.closeFlag == false
}
func (tcpConn *TCPConn) SetReadDeadline(d time.Duration) {
tcpConn.conn.SetReadDeadline(time.Now().Add(d))
}
func (tcpConn *TCPConn) SetWriteDeadline(d time.Duration) {
tcpConn.conn.SetWriteDeadline(time.Now().Add(d))
}

View File

@@ -19,6 +19,9 @@ type TcpService struct {
mapClientLocker sync.RWMutex
mapClient map[uint64] *Client
process processor.IProcessor
ReadDeadline time.Duration
WriteDeadline time.Duration
}
type TcpPackType int8
@@ -34,6 +37,8 @@ const Default_PendingWriteNum = 10000
const Default_LittleEndian = false
const Default_MinMsgLen = 2
const Default_MaxMsgLen = 65535
const Default_ReadDeadline = 180 //30s
const Default_WriteDeadline = 180 //30s
const (
MaxNodeId = 1<<10 - 1 //Uint10
@@ -89,6 +94,9 @@ func (tcpService *TcpService) OnInit() error{
tcpService.tcpServer.LittleEndian = Default_LittleEndian
tcpService.tcpServer.MinMsgLen = Default_MinMsgLen
tcpService.tcpServer.MaxMsgLen = Default_MaxMsgLen
tcpService.ReadDeadline = Default_ReadDeadline
tcpService.WriteDeadline = Default_WriteDeadline
MaxConnNum,ok := tcpCfg["MaxConnNum"]
if ok == true {
tcpService.tcpServer.MaxConnNum = int(MaxConnNum.(float64))
@@ -109,6 +117,17 @@ func (tcpService *TcpService) OnInit() error{
if ok == true {
tcpService.tcpServer.MaxMsgLen = uint32(MaxMsgLen.(float64))
}
readDeadline,ok := tcpCfg["ReadDeadline"]
if ok == true {
tcpService.ReadDeadline = time.Second*time.Duration(readDeadline.(float64))
}
writeDeadline,ok := tcpCfg["WriteDeadline"]
if ok == true {
tcpService.WriteDeadline = time.Second*time.Duration(writeDeadline.(float64))
}
tcpService.mapClient = make( map[uint64] *Client, tcpService.tcpServer.MaxConnNum)
tcpService.tcpServer.NewAgent = tcpService.NewClient
tcpService.tcpServer.Start()
@@ -166,6 +185,8 @@ func (slf *Client) Run() {
if slf.tcpConn == nil {
break
}
slf.tcpConn.SetReadDeadline(slf.tcpService.ReadDeadline)
bytes,err := slf.tcpConn.ReadMsg()
if err != nil {
log.Debug("read client id %d is error:%+v",slf.id,err)
@@ -201,6 +222,7 @@ func (tcpService *TcpService) SendMsg(clientId uint64,msg interface{}) error{
if err != nil {
return err
}
client.tcpConn.SetWriteDeadline(tcpService.WriteDeadline)
return client.tcpConn.WriteMsg(bytes)
}
@@ -239,6 +261,7 @@ func (tcpService *TcpService) SendRawMsg(clientId uint64,msg []byte) error{
return fmt.Errorf("client %d is disconnect!",clientId)
}
tcpService.mapClientLocker.Unlock()
client.tcpConn.SetWriteDeadline(tcpService.WriteDeadline)
return client.tcpConn.WriteMsg(msg)
}