4 #include <sys/socket.h>
7 #include <msp/core/systemerror.h>
8 #include <msp/io/handle_private.h>
9 #include <msp/strings/format.h>
10 #include <msp/time/rawtime_private.h>
11 #include <msp/time/units.h>
23 int err = WSAStartup(0x0002, &wsa_data);
25 std::cerr<<"Failed to initialize WinSock: "<<err<<'\n';
42 Socket::Socket(SocketHandle h, const SockAddr &paddr):
46 peer_addr(paddr.copy())
49 socklen_t size = sizeof(sockaddr_storage);
50 getsockname(handle, reinterpret_cast<sockaddr *>(&sa), &size);
51 local_addr = SockAddr::create(sa);
54 event = CreateEvent(0, false, false, 0);
60 Socket::Socket(Family af, int type, int proto):
65 handle = socket(af, type, proto);
68 event = CreateEvent(0, false, false, 0);
76 signal_flush_required.emit();
88 void Socket::set_block(bool b)
90 mode = (mode&~IO::M_NONBLOCK);
92 mode = (mode|IO::M_NONBLOCK);
96 ioctlsocket(handle, FIONBIO, &flag);
98 int flags = fcntl(handle, F_GETFL);
99 fcntl(handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
103 const IO::Handle &Socket::get_event_handle()
109 void Socket::bind(const SockAddr &addr)
112 unsigned size = addr.fill_sockaddr(sa);
114 int err = ::bind(handle, reinterpret_cast<sockaddr *>(&sa), size);
116 throw system_error("bind");
119 local_addr = addr.copy();
122 void Socket::set_timeout(const Time::TimeDelta &timeout)
125 timeval tv = Time::rawtime_to_timeval(timeout.raw());
126 set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
127 set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
129 DWORD msecs = static_cast<DWORD>(timeout/Time::msec);
130 set_option(SOL_SOCKET, SO_RCVTIMEO, &msecs, sizeof(DWORD));
131 set_option(SOL_SOCKET, SO_SNDTIMEO, &msecs, sizeof(DWORD));
135 const SockAddr &Socket::get_local_address() const
138 throw bad_socket_state("not bound");
142 const SockAddr &Socket::get_peer_address() const
145 throw bad_socket_state("not connected");
149 int Socket::set_option(int level, int optname, const void *optval, socklen_t optlen)
152 return setsockopt(handle, level, optname, reinterpret_cast<const char *>(optval), optlen);
154 return setsockopt(handle, level, optname, optval, optlen);
158 int Socket::get_option(int level, int optname, void *optval, socklen_t *optlen) const
161 return getsockopt(handle, level, optname, reinterpret_cast<char *>(optval), optlen);
163 return getsockopt(handle, level, optname, optval, optlen);
167 unsigned Socket::do_write(const char *buf, unsigned size)
170 throw bad_socket_state("not connected");
175 int ret = ::send(handle, buf, size, 0);
181 throw system_error("send");
187 unsigned Socket::do_read(char *buf, unsigned size)
190 throw bad_socket_state("not connected");
196 int ret = ::recv(handle, buf, size, 0);
202 throw system_error("recv");
204 else if(ret==0 && !eof_flag)
207 signal_end_of_file.emit();
208 set_events(IO::P_NONE);