]> git.stg.codes - stg.git/blob - stglibs/sgcp.lib/unix.cpp
02f7f5244ee001718f698a20eac3320a635c786f
[stg.git] / stglibs / sgcp.lib / unix.cpp
1 #include "unix.h"
2
3 using STG::SGCP::UNIXProto;
4
5 UNIXProto::UNIXProto(ba::io_service& ios)
6     : m_ios(ios),
7       m_acceptor(m_ios)
8 {
9 }
10
11 UNIXProto::~UNIXProto()
12 {
13     close(m_sock);
14 }
15
16 ConnectionPtr UNIXProto::connect(const std::string& address, uint16_t /*port*/)
17 {
18     bs::error_code ec;
19     ConnectionPtr conn = boost::make_shared(m_ios);
20     conn.socket().connect(ba::local::stream_protocol::enpoint(address), ec);
21     if (ec)
22         throw Error(ec.message());
23     conn->start();
24     return conn;
25 }
26
27 void UNIXProto::bind(const std::string& address, uint16_t /*port*/, Proto::AcceptHandler handler)
28 {
29     bs::error_code ec;
30     m_acceptor.bind(address, ec);
31     if (ec)
32         throw Error(ec.message());
33
34     UNIXConn* conn = new UNIXConn(m_ios);
35     m_acceptor.async_accept(conn->socket(), conn->endpoint(), boost::bind(&UNIXProto::m_handleAccept, this, conn, handler, boost::_1);
36 }
37
38 void UNIXProto::m_handleAccept(UNIXConn* conn, Proto::AcceptHandler handler, const boost::system::error_code& ec)
39 {
40     if (ec) {
41         delete conn;
42         handler(NULL, "", ec.message());
43         return;
44     }
45     handler(conn, conn->enpoint().path(), "");
46 }