openethereum/src/network/service.rs

55 lines
1.5 KiB
Rust
Raw Normal View History

2015-12-17 11:42:30 +01:00
use std::thread::{self, JoinHandle};
use mio::*;
use network::{Error, ProtocolHandler};
use network::host::{Host, HostMessage, PeerId, PacketId, ProtocolId};
2015-12-30 12:23:36 +01:00
/// IO Service with networking
2015-12-17 11:42:30 +01:00
pub struct NetworkService {
thread: Option<JoinHandle<()>>,
host_channel: Sender<HostMessage>
}
impl NetworkService {
2015-12-30 12:23:36 +01:00
/// Starts IO event loop
2015-12-17 11:42:30 +01:00
pub fn start() -> Result<NetworkService, Error> {
let mut event_loop = EventLoop::new().unwrap();
let channel = event_loop.channel();
let thread = thread::spawn(move || {
Host::start(&mut event_loop).unwrap(); //TODO:
});
Ok(NetworkService {
thread: Some(thread),
host_channel: channel
})
}
2015-12-30 12:23:36 +01:00
/// Send a message over the network. Normaly `HostIo::send` should be used. This can be used from non-io threads.
2015-12-17 11:42:30 +01:00
pub fn send(&mut self, peer: &PeerId, packet_id: PacketId, protocol: ProtocolId, data: &[u8]) -> Result<(), Error> {
try!(self.host_channel.send(HostMessage::Send {
peer: *peer,
packet_id: packet_id,
protocol: protocol,
data: data.to_vec()
}));
Ok(())
}
2015-12-30 12:23:36 +01:00
/// Regiter a new protocol handler with the event loop.
2015-12-17 11:42:30 +01:00
pub fn register_protocol(&mut self, handler: Box<ProtocolHandler+Send>, protocol: ProtocolId, versions: &[u8]) -> Result<(), Error> {
try!(self.host_channel.send(HostMessage::AddHandler {
handler: handler,
protocol: protocol,
versions: versions.to_vec(),
}));
Ok(())
}
}
impl Drop for NetworkService {
fn drop(&mut self) {
self.host_channel.send(HostMessage::Shutdown).unwrap();
self.thread.take().unwrap().join().unwrap();
}
}