在Go中模拟tcp连接 [英] Simulate a tcp connection in Go

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

问题描述

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


  1. 要读取的数据存储在字符串中

  2. 在写入数据时,我希望它被存储在某种缓冲区中,我可以稍后访问它。

有没有数据结构为此,还是一种简单的方法来制作一个?

解决方案

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

  type CloseableBuffer struct {
bytes.Buffer
}

并定义一个 Close 方法:

  func(b * CloseableBuffer)Close ()错误{
return nil
}


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. the data to be read is stored in a string
  2. whenever data is written, I'd like it to be stored in some kind of buffer which I can access later

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

解决方案

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
}

and define a Close method:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆