9

在 NodeJS 的最新几个版本(写作时为 v0.10.X)中,Streams API 进行了受欢迎的重新设计,我现在想开始使用它。

我想用一个实现协议的对象来包装套接字的输入输出。

所谓的 Duplex 接口,似乎就是任何可读可写的流(如套接字)。

尚不清楚 Duplexes 是否应该像 A 或 B,或者是否无关紧要。

   +---+        +---+
-->| A |-->     |   |-->
   +---+        | B |
                |   |<--
                +---+

对于具有两个可写和两个可读对象的正确代码结构/接口是什么?

+--------+   +----------+   +----
|       r|-->|w        r|-->|w    
| socket |   | protocol |   | rest of app
|       w|<--|r        w|<--|r    
+--------+   +----------+   +----

上图的问题是protocol对象需要两个单独的read方法和两个write方法。

在我的脑海中,我可以让协议产生“左”和“右”双工对象,或“输入”和“输出”双工对象(以不同的方式对其进行切片)。

这些是首选方式,还是有更好的解决方案?

4

2 回答 2

7
          |      app      |
          +---------------+
              ^       |
              |       V      
           +-----+ +-----+
           |     | |     |
+----------|     |-|     |-+
| protocol | .up | |.down| |
+----------|     |-|     |-+
           |     | |     |
           +-----+ +-----+
              ^       |
              |       V
          +---------------+
          |     socket    |

我的解决方案是创建一个 Protocol 类,它创建了一个 UpTransform和一个 Down Transform

Protocol 构造函数在构造 Up 和 Down 转换时传递一个引用(对自身)。然后_transform,每个 up 和 down 转换中的方法都可以根据需要调用push自身、另一个Transform或两者。公共状态可以保存在Protocol对象中。

于 2013-10-29T15:14:43.660 回答
1

A duplex stream is like your diagram B, at least for the user. A more complete view of a stream would be to include producer(source) with the consumer(user). See my previous answer. Try not to think both read/write from a consumer point of view.

What you are doing is building a thin layer over the socket for protocol, so your design is correct :

                         -------+     +----------+     +------
                               r|---->|         r|---->|      
                         socket |     | protocol |     | rest of app
                               w|<----|         w|<----|      
                         -------+     +----------+     +------

You can use duplex or transform for the protocol part.

                 +---------+--------+---------+       +------------------+ 
                 | _write->|        |         |r      |   Transform  ->  |r
                 |-----------Duplex-----------|       +------------------+    
                 |         |        | <-_read |w      |   <- Transform   |w
                 +---------+--------+---------+       +------------------+

process being your protocol related processing on incoming/outgoing data using internal _read, _write. Or you can transform streams. You would pipe protocol to socket and socket to protocol .

于 2013-10-16T18:53:11.080 回答