登录
首页 >  Golang >  Go问答

TCP连接超时异常数量过高

来源:stackoverflow

时间:2024-03-12 11:09:27 429浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《TCP连接超时异常数量过高》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在使用 go tcp 客户端连接到我们的 go tcp 服务器。

我能够连接到服务器并正确运行命令,但在尝试连接到 tcp 服务器或发送消息时,我的 tcp 客户端经常会报告异常大量的连续 tcp 连接错误连接后:

dial tcp kubernetes_node_ip:exposed_kubernetes_port:
connectex: a connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because connected
host has failed to respond.

read tcp unfamiliar_ip:unfamiliar_port->kubernetes_node_ip:exposed_kubernetes_port
wsarecv: a connection attempt failed because the connected party did not properly
respond after a period of time, or established connection failed because connected
host has failed to respond.

我说“异常高”是因为我认为这些错误发生的次数应该非常少(一小时内大约 5 次或更少)。请注意,我并不否认这种情况是由连接不稳定引起的,因为我还注意到可以快速连续运行多个命令而不会出现任何错误。

但是,我仍然会发布我的代码,以防万一我做错了什么。

下面是我的 tcp 客户端用于连接到我们的服务器的代码:

serveraddress, err := net.resolvetcpaddr("tcp", kubernetes_ip+":"+kubernetes_port)
if err != nil {     
    fmt.println(err)
    return
}

// never stop asking for commands from the user.
for {
    // connect to the server.
    serverconnection, err := net.dialtcp("tcp", nil, serveraddress)
    if err != nil {         
        fmt.println(err)
        continue
    }

    defer serverconnection.close()

    // added to prevent connection timeout errors, but doesn't seem to be helping
    // because said errors happen within just 1 or 2 minutes.
    err = serverconnection.setdeadline(time.now().add(10 * time.minute))
    if err != nil {         
        fmt.println(err)
        continue
    }

    // ask for a command from the user and convert to json bytes...

    // send message to server.
    _, err = serverconnection.write(clientmsgbytes)
    if err != nil {
        err = merry.wrap(err)
        fmt.println(merry.details(err))
        continue
    }

    err = serverconnection.closewrite()
    if err != nil {
        err = merry.wrap(err)
        fmt.println(merry.details(err))
        continue
    }

    // wait for a response from the server and print...
}

下面是我们的 tcp 服务器用来接受客户端请求的代码:

// we only supply the port so the ip can be dynamically assigned:
serveraddress, err := net.resolvetcpaddr("tcp", ":"+server_port)
if err != nil {     
    return err
}

tcplistener, err := net.listentcp("tcp", serveraddress)
if err != nil {     
    return err
}

defer tcplistener.close()

// never stop listening for client requests.
for {
    clientconnection, err := tcplistener.accepttcp()
    if err != nil {         
        fmt.println(err)
        continue
    }

    go func() {
        // add client connection to job queue.
        // note that `clientconnections` is a buffered channel with a size of 1500.
        // since i am the only user connecting to our server right now, i do not think
        // this is a channel blocking issue.
        clientconnections <- clientconnection
    }()
}

下面是我们的 tcp 服务器用来处理客户端请求的代码:

defer clientConnection.Close()

// Added to prevent connection timeout errors, but doesn't seem to be helping
// because said errors happen within just 1 or 2 minutes.
err := clientConnection.SetDeadline(time.Now().Add(10 * time.Minute))
if err != nil {     
    return err
}

// Read full TCP message.
// Does not stop until an EOF is reported by `CloseWrite()`
clientMsgBytes, err := ioutil.ReadAll(clientConnection)
if err != nil {
    err = merry.Wrap(err)
    return nil, err
}

// Process the message bytes...

我的问题是:

  1. 我在上面的代码中做错了什么,或者上面的代码对于基本的 tcp 客户端-服务器操作来说足够了吗?

  2. tcp 客户端和 tcp 服务器都具有延迟关闭其单个连接的代码可以吗?

  3. 我似乎记得在循环内调用 defer 没有任何作用。在开始新连接之前如何正确关闭客户端连接?

一些额外信息:

  • tcp 服务器不会记录上述错误,因此除了 连接不稳定,这也可能是 kubernetes/docker 相关问题。

解决方案


看来这段代码并没有像你想象的那样起作用。连接关闭的 defer 语句仅在函数返回时发生,而不是在迭代结束时发生。据我所知,您正在客户端创建大量连接,这可能是问题所在。

serveraddress, err := net.resolvetcpaddr("tcp", kubernetes_ip+":"+kubernetes_port)
if err != nil {     
    fmt.println(err)
    return
}

// never stop asking for commands from the user.
for {
    // connect to the server.
    serverconnection, err := net.dialtcp("tcp", nil, serveraddress)
    if err != nil {         
        fmt.println(err)
        continue
    }

    defer serverconnection.close()

    // added to prevent connection timeout errors, but doesn't seem to be helping
    // because said errors happen within just 1 or 2 minutes.
    err = serverconnection.setdeadline(time.now().add(10 * time.minute))
    if err != nil {         
        fmt.println(err)
        continue
    }

    // ask for a command from the user and send to the server...

    // wait for a response from the server and print...
}

我建议这样写:

func start() {
    serveraddress, err := net.resolvetcpaddr("tcp", kubernetes_ip+":"+kubernetes_port)
    if err != nil {     
        fmt.println(err)
        return
    }
    for {
        if err := listen(serveraddress); err != nil {
            fmt.println(err)
        }
    }
}

func listen(serveraddress string) error {
     // connect to the server.
     serverconnection, err := net.dialtcp("tcp", nil, serveraddress)
     if err != nil {         
         fmt.println(err)
         continue
     }

    defer serverconnection.close()

    // never stop asking for commands from the user.
    for {
        // added to prevent connection timeout errors, but doesn't seem to be helping
        // because said errors happen within just 1 or 2 minutes.
        err = serverconnection.setdeadline(time.now().add(10 * time.minute))
        if err != nil {         
           fmt.println(err)
           return err
        }

        // ask for a command from the user and send to the server...

        // wait for a response from the server and print...
    }
}

此外,您应该保持单个连接或连接池打开,而不是立即打开和关闭连接。然后,当您发送消息时,您会从池中获取连接(或单个连接),然后编写消息并等待响应,然后将连接释放到池中。

类似的事情:

res, err := c.Send([]byte(`my message`))
if err != nil {
    // handle err
}

// the implementation of send
func (c *Client) Send(msg []byte) ([]byte, error) {
    conn, err := c.pool.Get() // returns a connection from the pool or starts a new one
    if err != nil {
        return nil, err
    }
    // send your message and wait for response
    // ...
    return response, nil
}

本篇关于《TCP连接超时异常数量过高》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>