]> git.tdb.fi Git - libs/net.git/blob - source/clientsocket.cpp
Correct poll usage
[libs/net.git] / source / clientsocket.cpp
1 #ifndef WIN32
2 #include <cerrno>
3 #include <sys/socket.h>
4 #endif
5 #include <msp/core/systemerror.h>
6 #include "clientsocket.h"
7 #include "socket_private.h"
8
9 namespace Msp {
10 namespace Net {
11
12 ClientSocket::ClientSocket(Family af, int type, int proto):
13         Socket(af, type, proto),
14         connecting(false),
15         connected(false),
16         peer_addr(0)
17 { }
18
19 ClientSocket::ClientSocket(const Private &p, const SockAddr &paddr):
20         Socket(p),
21         connecting(false),
22         connected(true),
23         peer_addr(paddr.copy())
24 { }
25
26 ClientSocket::~ClientSocket()
27 {
28         signal_flush_required.emit();
29
30         delete peer_addr;
31 }
32
33 const SockAddr &ClientSocket::get_peer_address() const
34 {
35         if(peer_addr==0)
36                 throw bad_socket_state("not connected");
37         return *peer_addr;
38 }
39
40 unsigned ClientSocket::do_write(const char *buf, unsigned size)
41 {
42         if(!connected)
43                 throw bad_socket_state("not connected");
44
45         if(size==0)
46                 return 0;
47
48         int ret = ::send(priv->handle, buf, size, 0);
49         if(ret<0)
50         {
51                 if(errno==EAGAIN)
52                         return 0;
53                 else
54                         throw system_error("send");
55         }
56
57         return ret;
58 }
59
60 unsigned ClientSocket::do_read(char *buf, unsigned size)
61 {
62         if(!connected)
63                 throw bad_socket_state("not connected");
64
65         if(size==0)
66                 return 0;
67
68         int ret = ::recv(priv->handle, buf, size, 0);
69         if(ret<0)
70         {
71                 if(errno==EAGAIN)
72                         return 0;
73                 else
74                         throw system_error("recv");
75         }
76         else if(ret==0 && !eof_flag)
77         {
78                 eof_flag = true;
79                 signal_end_of_file.emit();
80                 set_events(IO::P_NONE);
81         }
82
83         return ret;
84 }
85
86 } // namespace Net
87 } // namespace Msp