【问题标题】:Golang TCP Server - Exchange Data between ClientsGolang TCP 服务器 - 在客户端之间交换数据
【发布时间】:2019-09-16 07:39:28
【问题描述】:

我希望在 go 中实现一个 TCP 服务器,它应该能够从一个客户端接收数据并将其发送到另一个客户端。实现这一目标的正确方法是什么?我尝试了以下代码:

astSrc := *addr + ":" + strconv.Itoa(*astPort)
astListener, _ := net.Listen("tcp", astSrc)
fmt.Printf("Listening on %s for Client Connections.\n", astSrc)

defer astListener.Close()

pmsSrc := *addr + ":" + strconv.Itoa(*pmsPort)
pmsListener, _ := net.Listen("tcp", pmsSrc)
fmt.Printf("Listening on %s for DB Connections.\n", pmsSrc)

defer pmsListener.Close()

for {
pmsConn, pmsErr := pmsListener.Accept()

if pmsErr != nil {
    fmt.Printf("Some connection error: %s\n", pmsErr)
}

go handlePMSConnection(pmsConn)

astConn, astErr := astListener.Accept()

if astErr != nil {
    fmt.Printf("Some connection error: %s\n", astErr)
}
go handleAstConnection(astConn, pmsConn)
}

我想为每个客户端使用 2 个不同的端口(astSrc - 这是一个短时间连接和 pmsSrc - 永久连接)并为每个客户端创建 2 个侦听器。我希望能够从连接到 astSrc 端口的 Client-1 接收消息,并将其传递给 Client-2(pmsSrc 端口)。到目前为止,此代码正在运行,但如果 client-1 已断开连接然后重新连接 - 服务器将不再接受任何消息。我不知道在同一个循环中处理两个连接是否正确,我认为这就是问题所在,但如果我从循环中取出一个连接,那么该连接将无法访问。你能指出我正确的方向吗?

【问题讨论】:

  • tcp 是双向的。您可以使用相同的电线读写。假设 Alice 和 Box,Alice 连接到 Bob,反之亦然,那么 Alice 可以读取 Bob 的消息并直接将其发送回 Bob。不过要小心,如果它们都互相呼应,那就是电线上的无限循环。

标签: go tcp connection


【解决方案1】:

问题看起来是你需要一个 pms 连接来获得每个 ast 连接,在循环中插入你对 ast 连接的接受可能会解决你的直接问题,像这样

for {
    pmsConn, pmsErr := pmsListener.Accept()

    if pmsErr != nil {
        fmt.Printf("Some connection error: %s\n", pmsErr)
    }

    go handlePMSConnection(pmsConn)
    for {
        astConn, astErr := astListener.Accept()

        if astErr != nil {
            fmt.Printf("Some connection error: %s\n", astErr)
        }
        go handleAstConnection(astConn, pmsConn)
    }
}

但是如果你丢失了 pms 连接会出现问题,如果你有多个 ast 连接会发生什么。并且您需要在 ast 连接之前连接 pms 连接。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2013-02-09
    • 2018-09-14
    • 1970-01-01
    • 2019-07-24
    • 2016-07-28
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多