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())
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法