duandi8613 2016-11-29 09:28 采纳率: 100%
浏览 767
已采纳

如何在GO中测试TCP断开连接

I do have a process receiving data from second local process. I need to test if connection errors are handled well AND if it automatically reconnects and keep receiving data after a disconnection.

To do so I am trying to make it disconnect abruptly or put the TCP connection in an error state from a unit test. As seen in this question to check if a connection is closed I am checking for data to come and test if it returns an error. I am not sure how to:

  • close the connection ungracefully
  • make it be in an error state

This is the essence of my data receiver:

    import (
        "bufio"
        "encoding/json"
        "fmt"
        "io"
        "net"
    )

    type Message struct {
        ID string `json:"id"`
    }

    func ReceiveData(listener Listener) {
        var tcpConn net.Conn
        var addr string = "127.0.0.1:9999"
        tcpConn, err := net.Dial("tcp", addr)
        socketReader := bufio.NewReader(tcpConn)
        decoder := json.NewDecoder(socketReader)

        for {
            var msg Message
            if err := decoder.Decode(&msg); err == io.EOF {
                listener.ProcessUpdate(Message{}, fmt.Errorf("Received EOF"), nil)
                tcpConn = nil
                return
            } else if err != nil {
                listener.ProcessUpdate(Message{}, nil, fmt.Errorf("Error decoding message: %s", err.Error()))
                tcpConn = nil
                return
        }

        // process message
        _ = msg

        // Test disconnection
        // This does not disconnect:
        // tcpConn = nil
        // This does but gracefully:
        // tcpConn.Close()
    }

I am not mocking the TCP connection as I'd like to try with the real data producer. If is needed I'll look at it.

  • 写回答

1条回答 默认 最新

  • dongyu4455 2016-11-29 11:59
    关注

    A solution is to set a deadline to the TCP connection itself:

    tcpConn.SetDeadline(time.Now())
    

    Later this will trigger a timeout error which can be caught with:

    err := decoder.Decode(&msg);
    if err != nil {
        if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
            fmt.Errorf("TCP timeout : %s", err.Error())
        } else {
            fmt.Errorf("Received error decoding message: %s", err.Error())
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装