在网上读和写Conn [英] Reading and writing on net.Conn

查看:63
本文介绍了在网上读和写Conn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从net.Conn读取和写入数据,但是由于我只有Read([] byte)和Write([] byte)函数,因此我很难找到辅助函数来完成此工作。

I am trying to read and write data from a net.Conn but since I have only Read([]byte) and Write([]byte) functions, I am finding quite hard to find helper functions to do this job.

我需要读写以下类型:


  • uint64

  • byte

  • uint32

  • UTF-8编码的字符串(第一个为uint32长度,后为字符串数据)

  • uint64
  • byte
  • uint32
  • UTF-8 encoded string ( first a uint32 length and the string data after)

简而言之

是否有类似Go程序包中的Java DataInputStream和DataOutputStream吗?

Is there anything like Java's DataInputStream and DataOutputStream in Go's packages ?

感谢和问候

推荐答案

您需要确定一种往返编组的格式。您可以选择采用自己的格式,也可以使用已经制作的格式。我强烈建议使用后者。

You need to decide on a format to marshal to and from. Your choices are to either roll your own format or to use one that was already made. I highly recommend the latter.

我以前在此处发布过go标准库中支持的许多格式:https://stackoverflow.com/a/13575325/727643

I have previously posted about many of the formats supported in the go standard library here: https://stackoverflow.com/a/13575325/727643

如果您决定自己滚动,则可以使用uint可以使用 encoding / binary 从[] byte中进行编码和解码。它为您提供了小端和大端的选择。可以使用 [] byte(str)将字符串直接转换为[] byte。最后,字节可以作为字节发送。

If you decide to roll your own, then uints can be encoded and decoded from []byte using encoding/binary. It gives you the option of both little and big endian. Strings can be converted directly to []byte using []byte(str). Finally, bytes can just be sent as bytes. No magic needed.

我会强调,编排自己的格式通常不是一个好主意。我倾向于默认情况下使用JSON,并且仅在可以显着提高性能并且相信这样做值得时才使用其他JSON。

I will stress that making up your own format is normally a bad idea. I tend to use JSON by default and use others only when I can get a significant performance increase and I believe it worth the time to do it.

这篇关于在网上读和写Conn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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