本文介绍了在 Go 中模拟 tcp 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Go 中,TCP 连接(net.Conn)是一个 io.ReadWriteCloser.我想通过模拟 TCP 连接来测试我的网络代码.我有两个要求:

In Go, a TCP connection (net.Conn) is a io.ReadWriteCloser. I'd like to test my network code by simulating a TCP connection. There are two requirements that I have:

  1. 要读取的数据存储在一个字符串中
  2. 每当写入数据时,我都希望将其存储在某种缓冲区中,以便稍后访问

是否有用于此的数据结构,或制作一个简单的方法?

Is there a data structure for this, or an easy way to make one?

推荐答案

为什么不使用 bytes.Buffer?它是一个 io.ReadWriter 并且有一个 String 方法来获取存储的数据.如果你需要让它成为 io.ReadWriteCloser,你可以定义你自己的类型:

Why not using bytes.Buffer? It's an io.ReadWriter and has a String method to get the stored data. If you need to make it an io.ReadWriteCloser, you could define you own type:

type CloseableBuffer struct {
    bytes.Buffer
}

并定义一个Close方法:

func (b *CloseableBuffer) Close() error {
    return nil
}

这篇关于在 Go 中模拟 tcp 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:11