]> git.tdb.fi Git - libs/net.git/blob - source/streamlistensocket.cpp
Header changes
[libs/net.git] / source / streamlistensocket.cpp
1 #include <cerrno>
2 #include <msp/core/refptr.h>
3 #include <msp/strings/format.h>
4 #include "streamlistensocket.h"
5 #include "streamsocket.h"
6
7 namespace Msp {
8 namespace Net {
9
10 StreamListenSocket::StreamListenSocket(Family af, int proto):
11         Socket(af, SOCK_STREAM, proto),
12         listening(false)
13 { }
14
15 int StreamListenSocket::connect(const SockAddr &)
16 {
17         throw Exception("Can't connect a listen socket");
18 }
19
20 void StreamListenSocket::listen(const SockAddr &addr, unsigned backlog)
21 {
22         bind(addr);
23
24         int err = ::listen(handle, backlog);
25         if(err==-1)
26                 throw SystemError("Unable to listen", errno);
27
28 #ifdef WIN32
29         WSAEventSelect(handle, event, FD_ACCEPT);
30 #endif
31         set_events(IO::P_INPUT);
32
33         listening = true;
34 }
35
36 StreamSocket *StreamListenSocket::accept()
37 {
38         if(!listening)
39                 throw InvalidState("Socket is not listening");
40
41         sockaddr_storage sa;
42         socklen_t size = sizeof(sockaddr_storage);
43         SocketHandle new_h = ::accept(handle, reinterpret_cast<sockaddr *>(&sa), &size);
44
45         RefPtr<SockAddr> paddr = SockAddr::create(sa);
46         return new StreamSocket(new_h, *paddr);
47 }
48
49 } // namespace Net
50 } // namespace Msp