英文:
Go. Get error i/o timeout in server program
问题
我写了一个简单的服务器程序来接收客户端的数据。有时候我会从函数中得到错误信息read tcp4 IP:PORT i/o timeout,我有点不明白是什么原因导致的。我在函数SetDeadline()
中设置了事件时间,但是没有超过。我展示了一部分我的代码,但我认为这已经足够了。
下面是我接收数据的主循环。
c := NewClient()
c.kickTime = time.Now()
func (c *Client) Listen() {
durationToClose := time.Minute * time.Duration(5)
c.conn.SetDeadline(c.kickTime.Add(c.durationToClose))
buffer := make([]byte, 1024)
for {
reqLen, err := c.conn.Read(buffer)
if err != nil || reqLen == 0 {
fmt.Printf(err)
break
}
if err = c.CheckData(buffer); err != nil {
fmt.Printf("something is bad")
} else {
result := c.PrepareDataToSendInOtherPlace(buffer)
go c.RecievedData(result)
}
c.conn.SetDeadline(c.kickTime.Add(c.durationToKick))
}
}
对我来说,唯一可疑的可能是PrepareDataToSendInOtherPlace()
和CheckData()
这两个额外的函数可能会占用一些CPU时间,然后客户端发送了新的数据,而服务器在执行其他操作时拒绝了连接。这只是我的猜测,但我不确定。
英文:
I wrote simply server program to received data form client. I little not understand what sometimes I get error read tcp4 IP:PORT i/o timeout from function
int, err := conn.Read([]byte)
event time set in function SetDeadline()
not was exceeded. I present some part of my code, but I think that this is will enough.
main loop where I receive data is below.
c := NewClient()
c.kickTime: time.Now()
func (c *Client) Listen(){
durationToClose := time.Minute*time.Duration(5),
c.conn.SetDeadline(c.kickTime.Add(c.durationToClose))
buffer := make([]byte, 1024)
for{
reqLen, err := c.conn.Read(buffer)
if err != nil || reqLen == 0 {
fmt.Printf(err)
break
}
if err = c.CheckData(buffer) ; err != nil{
fmt.Printf("something is bad")
}else{
result := c.PrepareDataToSendInOtherPlace(buffer)
go c.RecievedData(result)
}
c.conn.SetDeadline(c.kickTime.Add(c.durationToKick))
}
}
For me only suspicious can be additional function as PrepareDataToSendInOtherPlace() , CheckData()
which may take some times CPU, and then new data was be send by client, and server at the time doing something else and rejects connect. This is only my supposition, but I'm not sure.
答案1
得分: 1
语法错误和未声明的变量暂且不提,你展示的代码无法无限地推进读写截止时间。它最长只能运行到第一个time.Now()
之后的固定时间段(c.kickTime.Add(c.durationToKick)
)。你可能想要这样的代码:
c.conn.SetDeadline(time.Now().Add(c.durationToKick))
英文:
Syntax errors and undeclared variables aside, what you're showing us can't possibly be walking the Read/Write deadline forward indefinitely.
The longest this could run is until a fixed duration after the first time.Now()
(c.kickTime.Add(c.durationToKick)
). You probably want something like:
c.conn.SetDeadline(time.Now().Add(c.durationToKick))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论