Files
the-way-to-go_ZH_CN/eBook/15.10.md
2019-07-18 20:54:20 -07:00

38 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 15.10 基于网络的通道 netchan
备注Go 团队决定改进并重新打造 `netchan` 包的现有版本,它已被移至 `old/netchan``old/` 目录用于存放过时的包代码,它们不会成为 Go 1.x 的一部分。本节仅出于向后兼容性讨论 `netchan` 包的概念。
一项和 `rpc` 密切相关的技术是基于网络的通道。类似 14 章所使用的通道都是本地的,它们仅存在于被执行的机器内存空间中。`netchan` 包实现了类型安全的网络化通道:它允许一个通道两端出现由网络连接的不同计算机。其实现原理是,在其中一台机器上将传输数据发送到通道中,那么就可以被另一台计算机上同类型的通道接收。一个导出器(`exporter`)会按名称发布(一组)通道。导入器(`importer`)连接到导出的机器,并按名称导入这些通道。之后,两台机器就可按通常的方式来使用通道。网络通道不是同步的,它们类似于带缓存的通道。
发送端示例代码如下:
```go
exp, err := netchan.NewExporter("tcp", "netchanserver.mydomain.com:1234")
if err != nil {
log.Fatalf("Error making Exporter: %v", err)
}
ch := make(chan myType)
err := exp.Export("sendmyType", ch, netchan.Send)
if err != nil {
log.Fatalf("Send Error: %v", err)
}
```
接收端示例代码如下:
```go
imp, err := netchan.NewImporter("tcp", "netchanserver.mydomain.com:1234")
if err != nil {
log.Fatalf("Error making Importer: %v", err)
}
ch := make(chan myType)
err = imp.Import("sendmyType", ch, netchan.Receive)
if err != nil {
log.Fatalf("Receive Error: %v", err)
}
```
## 链接
- [目录](directory.md)
- 上一节:[用 rpc 实现远程过程调用](15.9.md)
- 下一节:[与 websocket 通信](15.11.md)