What you are wasting today is tomorrow for those who died yesterday; what you hate now is the future you can not go back.
你所浪费的今天是昨天死去的人奢望的明天; 你所厌恶的现在是未来的你回不去的曾经。
如何通过简单的tcp / ip连接将数据从进程a发送到进程b?
在许多情况下,使用更高级别的网络协议无疑会做得更好,从而将所有技术细节隐藏在一个奇特的API下面。并且已经有很多可供选择的,取决于需要:消息队列协议,grpc,protobuf,flatbuffers,restful web api,websockets等等。
但是,在某些情况下(特别是在小型项目中),您选择的任何方法可能看起来完全过大。
1. connections是一个io流
net.Conn实现了 io.Reader, io.Writer, io.Closer接口。 所以我们这是像使用io流一样来使用TCP 链接。
首先我们来看看 Golang源码的 io 包中的这三个类型的定义:
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type Closer interface {
Close() error
}
再来看看Golang源码中net包Conn 类型的定义:
type Conn interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
Close() error
LocalAddr() Addr
RemoteAddr() Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
}
那么我们可以通过TCP链接发送string字符串了, 但是如何发送复杂的类型呢?
2. Go 编码复杂类型
当涉及通过网络发送结构化数据时,很容易想到json, 但是Go自身提供了一个gob包直接在io流数据上操作,序列化和反序列化数据,不需要json那样添加标签, 然后再费力的json.Unmarshal()转为二进制数据.