orientdb_client/sync/network/
conn.rs1use crate::common::protocol::messages::request::HandShake;
2use crate::common::protocol::messages::{Request, Response};
3use crate::sync::protocol::WiredProtocol;
4use crate::OrientResult;
5use byteorder::{BigEndian, ReadBytesExt};
6use std::io::Write;
7use std::net::Shutdown;
8use std::net::{SocketAddr, TcpStream};
9
10pub struct Connection {
11 stream: TcpStream,
12 protocol: WiredProtocol,
13}
14
15impl Connection {
16 pub fn connect(addr: &SocketAddr) -> OrientResult<Self> {
17 let mut stream = TcpStream::connect(addr)?;
18 let p = stream.read_i16::<BigEndian>()?;
19 let protocol = WiredProtocol::from_version(p)?;
20 let conn = Connection { stream, protocol };
21 conn.handshake()
22 }
23
24 fn handshake(mut self) -> OrientResult<Connection> {
25 let handshake = HandShake {
26 p_version: self.protocol.version,
27 name: String::from("Rust Driver"),
28 version: String::from("0.1"),
29 };
30 self.send_and_forget(handshake.into())?;
31 Ok(self)
32 }
33
34 pub fn close(&mut self) -> OrientResult<()> {
35 self.stream.shutdown(Shutdown::Both)?;
36 Ok(())
37 }
38
39 pub fn send_and_forget(&mut self, request: Request) -> OrientResult<()> {
40 let buf = self.protocol.encode(request)?;
41 self.stream.write_all(buf.as_slice())?;
42 Ok(())
43 }
44 pub fn send(&mut self, request: Request) -> OrientResult<Response> {
45 self.send_and_forget(request)?;
46 self.protocol.decode(&mut self.stream)
47 }
48}