duandi8613
2016-11-29 09:28
浏览 593
已采纳

如何在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())
        }
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题