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