8
8
# message-io
9
9
` message-io ` is an event-driven message library to build network applications ** easy** and ** fast** .
10
10
The library handles the internal OS socket in order to offer a simple event message API to the user.
11
- It also allows you to make an adapter for your own transport protocol following some [ rules ] ( #custom-adapter ) ,
12
- delegating to the library the tedious asynchrony and thread management.
11
+ It also allows you to make an adapter for your own transport protocol following some
12
+ [ rules ] ( #custom-adapter ) , delegating to the library the tedious asynchrony and thread management.
13
13
14
14
<p align =" center " >
15
15
<img src =" https://docs.google.com/drawings/d/e/2PACX-1vSPmycMsWoQq60MPEODcakFQVPkDwVy98AnduTswFNPGBB5dpbIsSCHHBhS2iEuSUtbVaYQb7zgfgjO/pub?w=653&h=305 " width =" 653 " />
@@ -19,15 +19,15 @@ If you find a problem using the library or you have an improvement idea,
19
19
do not hesitate to open an issue. ** Any contribution is welcome!**
20
20
21
21
## Motivation
22
- Managing sockets is hard because you need to fight with threads, concurrency,
23
- IO errors that come from the OS (which are really difficult to understand in some situations), encoding.. .
24
- And if you make use of * non-blocking* sockets, it adds a new layer of complexity:
25
- synchronize the events that come asynchronously from the OS poll .
22
+ Managing sockets is hard because you need to fight with threads, concurrency, full duplex, encoding,
23
+ IO errors that come from the OS (which are really difficult to understand in some situations), etc .
24
+ If you make use of * non-blocking* sockets, it adds a new layer of complexity:
25
+ synchronize the events that come asynchronously from the Operative System .
26
26
27
27
` message-io ` offers an easy way to deal with all these mentioned problems,
28
28
making them transparently for you,
29
29
the programmer that wants to make an application with its own problems.
30
- For that, ` message-io ` offers a simple API and give only two concepts to understand:
30
+ For that, the library gives you a simple API with two concepts to understand:
31
31
** messages** (the data you send and receive), and ** endpoints** (the recipients of that data).
32
32
This abstraction also offers the possibility to use the same API independently
33
33
of the transport protocol used.
@@ -44,42 +44,43 @@ You could change the transport of your application in literally one line.
44
44
[ tungstenite-rs] ( https://github.com/snapview/tungstenite-rs ) .
45
45
- Customizable: ` message-io ` doesn't have the transport you need?
46
46
Add easily and [ adapter] ( #custom-adapter ) .
47
- - FIFO events with timers and priority.
47
+ - Custom FIFO events with timers and priority.
48
48
- Easy, intuitive and consistent API:
49
49
- Follows [ KISS principle] ( https://en.wikipedia.org/wiki/KISS_principle ) .
50
50
- Abstraction from transport layer: do not think about sockets, think about messages and endpoints.
51
51
- Only two main entities to use:
52
- - an extensible
53
- [ ` Eventqueue ` ] ( https://docs.rs/message-io/latest/message_io/events/struct.EventQueue.html )
54
- to manage all events synchronously,
55
- - a [ ` Network ` ] ( https://docs.rs/message-io/latest/message_io/network/struct.Network.html )
56
- to manage all connections (connect, listen, remove, send, receive).
52
+ - a [ ` NodeHandler ` ] ( https://docs.rs/message-io/latest/message_io/node/struct.NodeHandler.html )
53
+ to manage all connections (connect, listen, remove, send) and signals (timers, priority).
54
+ - a [ ` NodeListener ` ] ( https://docs.rs/message-io/latest/message_io/node/struct.NodeListener.html )
55
+ to process all signals and events from the network.
57
56
- Forget concurrence problems: handle all connection and listeners from one thread:
58
57
"One thread to rule them all".
59
58
- Easy error handling:
60
59
do not deal with dark internal ` std::io::Error ` when send/receive from the network.
61
60
- High performance:
62
- - Using non-blocking sockets from one thread allows to not waste memory and time
63
- synchonizing multiple threads.
61
+ - Non-blocking sockets: scale the application without wasting memory and time synchonizing
62
+ multiple threads.
63
+ - Zero-copy message. You write and read directly from the internal OS socket buffer without any copy in the middle by the library.
64
64
- Full duplex: simultaneous reading/writing operations over same internal OS sockets.
65
65
66
66
## Getting started
67
67
Add to your ` Cargo.toml ` (all the transports included by default):
68
68
``` toml
69
69
[dependencies ]
70
- message-io = " 0.11 "
70
+ message-io = " 0.12 "
71
71
```
72
72
If you ** only** want to use a subset of the available transport battery,
73
73
you can select them by their associated features ` tcp ` , ` udp ` , and ` websocket ` .
74
74
For example, in order to include only * TCP* and * UDP* , add to your ` Cargo.toml ` :
75
75
``` toml
76
76
[dependencies ]
77
- message-io = { version = " 0.11 " , default-features = false , features = [" tcp" , " udp" ] }
77
+ message-io = { version = " 0.12 " , default-features = false , features = [" tcp" , " udp" ] }
78
78
```
79
79
80
- ** Warning** : If you comming from ** 0.9.4 o less** , note that ` Transport::Tcp ` has been renamed
81
- to ` Transport::FramedTcp ` to be more according to its behaviour.
82
- See more [ here] ( https://docs.rs/message-io/latest/message_io/network/enum.Transport.html ) .
80
+ ** Warning** : Version ** 0.12** comes with important API changes ([ changelog] ( CHANGELOG.md ) )
81
+ in order to reach [ zero-copy message] ( https://github.com/lemunozm/message-io/issues/61 ) goal.
82
+ If you find problems porting your application to this version,
83
+ check the examples folder, API docs, and don't hesitate to open an issue.
83
84
84
85
### Documentation
85
86
- [ API documentation] ( https://docs.rs/message-io/ )
@@ -102,73 +103,76 @@ It is capable to manage several client connections and listen from 3 differents
102
103
at the same time.
103
104
104
105
``` rust,no_run
105
- use message_io::network::{Network, NetEvent, Transport};
106
+ use message_io::node::{self};
107
+ use message_io::network::{NetEvent, Transport};
106
108
107
109
fn main() {
108
- // Create a Network with an associated event queue for reading its events.
109
- let (mut network, mut events) = Network::split();
110
-
111
- // Listen for TCP, UDP and WebSocket messages.
112
- network.listen(Transport::FramedTcp, "0.0.0.0:3042").unwrap(); // Tcp encoded for packets
113
- network.listen(Transport::Udp, "0.0.0.0:3043").unwrap();
114
- network.listen(Transport::Ws, "0.0.0.0:3044").unwrap();
115
-
116
- loop {
117
- match events.receive() { // Read the next event or wait until have it.
118
- NetEvent::Message(endpoint, data) => {
119
- println!("Received: {}", String::from_utf8_lossy(&data));
120
- network.send(endpoint, &data);
121
- },
122
- NetEvent::Connected(_endpoint, _) => println!("Client connected"), // Tcp or Ws
123
- NetEvent::Disconnected(_endpoint) => println!("Client disconnected"), //Tcp or Ws
124
- }
125
- }
110
+ // Create a node, the main message-io entity. It is divided in 2 parts:
111
+ // The 'handler', used to make actions (connect, send messages, signals, stop the node...)
112
+ // The 'listener', used to read events from the network or signals.
113
+ let (handler, listener) = node::split::<()>();
114
+
115
+ // Listen for TCP, UDP and WebSocket messages at the same time.
116
+ handler.network().listen(Transport::FramedTcp, "0.0.0.0:3042").unwrap();
117
+ handler.network().listen(Transport::Udp, "0.0.0.0:3043").unwrap();
118
+ handler.network().listen(Transport::Ws, "0.0.0.0:3044").unwrap();
119
+
120
+ // Read incoming network events.
121
+ listener.for_each(move |event| match event.network() {
122
+ NetEvent::Connected(_endpoint, _) => println!("Client connected"), // Tcp or Ws
123
+ NetEvent::Message(endpoint, data) => {
124
+ println!("Received: {}", String::from_utf8_lossy(data));
125
+ handler.network().send(endpoint, data);
126
+ },
127
+ NetEvent::Disconnected(_endpoint) => println!("Client disconnected"), //Tcp or Ws
128
+ });
126
129
}
127
130
```
128
131
129
132
### Echo client
130
133
The following example shows a client that can connect to the previous server.
131
134
It sends a message each second to the server and listen its echo response.
132
135
Changing the ` Transport::FramedTcp ` to ` Udp ` or ` Ws ` will change the underlying transport used.
133
- Also, you can create the number of connections you want at the same time, without any extra thread.
136
+ You can create the number of connections you want at the same time, without any extra thread.
134
137
135
138
``` rust,no_run
136
- use message_io::network::{Network, NetEvent, Transport};
139
+ use message_io::node::{self, NodeEvent};
140
+ use message_io::network::{NetEvent, Transport};
141
+ use std::time::Duration;
137
142
138
- enum Event {
139
- Net(NetEvent),
140
- Tick,
143
+ enum Signal {
144
+ Greet,
141
145
// Any other app event here.
142
146
}
143
147
144
148
fn main() {
145
- // The split_and_map() version allows to combine network events with your application events.
146
- let (mut network, mut events) = Network::split_and_map(|net_event| Event::Net(net_event));
149
+ let (handler, listener) = node::split();
147
150
148
151
// You can change the transport to Udp or Ws (WebSocket).
149
- let (server, _) = network.connect(Transport::FramedTcp, "127.0.0.1:3042").unwrap();
150
-
151
- events.sender().send(Event::Tick); // Start sending
152
- loop {
153
- match events.receive() {
154
- Event::Net(net_event) => match net_event { // event from the network
155
- NetEvent::Message(_endpoint, data) => {
156
- println!("Received: {}", String::from_utf8_lossy(&data));
157
- },
158
- _ => (),
159
- }
160
- Event::Tick => { // computed every second
161
- network.send(server, "Hello server!".as_bytes());
162
- events.sender().send_with_timer(Event::Tick, std::time::Duration::from_secs(1));
152
+ let (server, _) = handler.network().connect(Transport::FramedTcp, "127.0.0.1:3042").unwrap();
153
+
154
+ handler.signals().send(Signal::Greet); // Start sending
155
+
156
+ listener.for_each(move |event| match event {
157
+ NodeEvent::Signal(signal) => match signal {
158
+ Signal::Greet => { // computed every second
159
+ handler.network().send(server, "Hello server!".as_bytes());
160
+ handler.signals().send_with_timer(Signal::Greet, Duration::from_secs(1));
163
161
}
164
162
}
165
- }
163
+ NodeEvent::Network(net_event) => match net_event {
164
+ NetEvent::Message(_endpoint, data) => {
165
+ println!("Received: {}", String::from_utf8_lossy(data));
166
+ },
167
+ _ => unreachable!(), // Connected and Disconnected are only generated by listening
168
+ }
169
+ });
166
170
}
167
171
```
168
172
169
173
## Test it yourself!
170
174
Clone the repository and test the * Ping Pong* example
171
- (similar to the * echo * example but more vitaminized).
175
+ (similar to the * README * example but more vitaminized).
172
176
173
177
Run the server:
174
178
``` sh
@@ -196,12 +200,12 @@ If a transport protocol can be built in top of [`mio`](https://github.com/tokio-
196
200
(most of the existing protocol libraries can), then you can add it to ` message-io ` ** really easy** :
197
201
198
202
1 . Add your * adapter* file in ` src/adapters/<my-transport-protocol>.rs ` that implements the
199
- traits that you find [ here] ( https://docs.rs/message-io/latest/message_io/adapter/index.html ) .
203
+ traits that you find [ here] ( https://docs.rs/message-io/latest/message_io/network/ adapter/index.html ) .
200
204
It contains only 7 mandatory functions to implement (see the [ template] ( src/adapters/template.rs ) ),
201
205
and take little more than 150 lines to implement an adapter file.
202
206
203
- 1 . Add a new field in the ` Transport ` enum found in [ src/transport.rs ] ( src/transport.rs )
204
- to register your new adapter.
207
+ 1 . Add a new field in the ` Transport ` enum found in
208
+ [ src/network/transport.rs ] ( src/network/transport.rs ) to register your new adapter.
205
209
206
210
That's all.
207
211
You can use your new transport with the ` message-io ` API like any other.
0 commit comments