如果客户端在 10 秒内没有响应,我如何通过超时关闭连接?
How I can close the connection by timeout if the client doesn't respond in 10 seconds?
我有代码(我用https://github.com/fiorix/go-smpp):
// -----------------------------------------------
// handleConnection new clients.
// -----------------------------------------------
func (_srv *ServerSmpp) handleConnection(_cfg *ConfigSmpp, c *conn) {
defer c.Close()
if err := _srv.auth(_cfg, c); err != nil {
if err != io.EOF {
log.Printf("smpp_server: server auth failed: %s\n", err)
}
return
}
notify := make(chan error)
go func() {
for {
pb, err := c.Read()
if err != nil {
notify <- err
return
}
err = _srv.Handler(_srv.RemoteProvider, c, pb)
if err != nil {
fmt.Printf("%s\n", err)
notify <- err
return
}
}
}()
for {
select {
case err:= <-notify:
if io.EOF == err {
fmt.Printf("Smpp server (read): %s\n", err)
return
}
case <-time.After(time.Second * 10):
fmt.Printf("Client disconnected by timeout.\n")
return
}
}
}
调用 handleConnection 的代码:
func (_srv *ServerSmpp) Serve(_cfg *ConfigSmpp) {
for {
client, err := _srv.NetListener.Accept()
if err != nil {
break
}
c := newConn(client)
go _srv.handleConnection(_cfg, c)
}
}
当这段代码工作时,服务器会在超时 10 秒时断开所有客户端,但是当它在 10 秒内不起作用时我如何断开客户端?
您的 client
对象似乎是 net.Conn
,
在阻塞 client.Read()
之前,选择一种使用适当的 time.Time
值调用 client.SetReadDeadline()
的方法:
c.client.SetDeadline( time.Now().Add(10 * time.Second )
pb, err := c.Read() { ...
我有代码(我用https://github.com/fiorix/go-smpp):
// -----------------------------------------------
// handleConnection new clients.
// -----------------------------------------------
func (_srv *ServerSmpp) handleConnection(_cfg *ConfigSmpp, c *conn) {
defer c.Close()
if err := _srv.auth(_cfg, c); err != nil {
if err != io.EOF {
log.Printf("smpp_server: server auth failed: %s\n", err)
}
return
}
notify := make(chan error)
go func() {
for {
pb, err := c.Read()
if err != nil {
notify <- err
return
}
err = _srv.Handler(_srv.RemoteProvider, c, pb)
if err != nil {
fmt.Printf("%s\n", err)
notify <- err
return
}
}
}()
for {
select {
case err:= <-notify:
if io.EOF == err {
fmt.Printf("Smpp server (read): %s\n", err)
return
}
case <-time.After(time.Second * 10):
fmt.Printf("Client disconnected by timeout.\n")
return
}
}
}
调用 handleConnection 的代码:
func (_srv *ServerSmpp) Serve(_cfg *ConfigSmpp) {
for {
client, err := _srv.NetListener.Accept()
if err != nil {
break
}
c := newConn(client)
go _srv.handleConnection(_cfg, c)
}
}
当这段代码工作时,服务器会在超时 10 秒时断开所有客户端,但是当它在 10 秒内不起作用时我如何断开客户端?
您的 client
对象似乎是 net.Conn
,
在阻塞 client.Read()
之前,选择一种使用适当的 time.Time
值调用 client.SetReadDeadline()
的方法:
c.client.SetDeadline( time.Now().Add(10 * time.Second )
pb, err := c.Read() { ...