-
Notifications
You must be signed in to change notification settings - Fork 448
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
52 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
# 路由压缩 | ||
|
||
***状态: 草稿*** | ||
|
||
## 为什么需要路由压缩? | ||
|
||
在实际编程中,网络带宽的有效数据负载率是一个值得考虑的问题。对于移动客户端来说,网络资源往往不是很丰富,为 | ||
了尽可能地节省网络资源,往往需要尽大可能地增加数据包的有效数据率。 | ||
|
||
以我们的聊天应用为例,当客户端发起聊天时,需要指定处理其请求的服务器的路由信息,示例如下: | ||
|
||
```javascript | ||
|
||
nano.request('Room.Join', | ||
//... | ||
); | ||
|
||
``` | ||
这个路由信息指出,处理这个请求的应该是Room组件的Join方法。当服务器给客户端推送消息的时候,同样也需要指 | ||
明客户端的路由信息,在例子聊天应用中有onAdd,onLeave等。考虑当用户发起聊天的信息很短的时候,比如用户仅 | ||
仅发了一个字,而我们在传输的时候一样要加上一个完整的路由信息,这样将造成实际传输中,有效数据率极低,网 | ||
络资源被大量的额外信息浪费。最直接的想法就是缩短路由信息,对服务端的路由信息来说,由于当服务器确定后,其 | ||
路由信息就确定了,对于客户端来说,虽然可以起很短的名字,但是很容易造成程序不可读。 | ||
|
||
## 如何实现? | ||
|
||
针对这种情况,`nano`提供了基于字典的路由信息压缩。 | ||
|
||
* 对于服务端,`nano`会扫描所有的Handler信息 | ||
* 对于客户端,用户需要配置一个路由映射表 | ||
|
||
通过这两种方式,`nano`会拿到所有的客户端和服务端的路由信息,然后将每一个路由信息都映射为一个小整数,从1 | ||
开始映射,累加。在目前的实现中,如果使用了路由信息压缩,在客户端与服务器建立连接的握手过程中,服务器会将 | ||
整个字典传给客户端,这样在以后的通信中,对于路由信息,将全部使用定义的小整数进行标记,大大地减少了额外信 | ||
息开销。 | ||
|
||
对于dictionary中添加的客户端路由,会使用路由压缩。如果有客户端的推送路由没有加入到dictionary中,会怎 | ||
么样呢?不用怕,对于在dictionary中找不到的路由信息,`nano`还是会使用原来不压缩的路由。 | ||
|
||
## 小结 | ||
到目前位置,我们客户端与服务器之间使用的消息传输格式一直都是json。实际上,虽然json很方便,但是由于其还带 | ||
了一些字段信息,在客户端和服务端数据包格式统一的情况下,这些字段信息是可以省略的,可以直接传输具体的消息, | ||
也就是说不再以字符串作为通信格式了,直接发送有效的二进制数据将会更好地减少额外开销,`nano`可以使用Protobuf | ||
作为二进制协议, 可以通过: | ||
```go | ||
nano.SetSerializer(protobuf.NewSerializer()) | ||
``` | ||
让nano选择Protobuf作为二进制协议 | ||
|
||
***Copyright***:Parts of above content and figures come from [Pomelo Route compression](https://github.com/NetEase/pomelo/wiki/Route-compression) |