Improved socket error handling.

This commit is contained in:
Gunnar Beutner 2012-04-04 16:02:19 +02:00
parent 6a42ac0fe5
commit 8e7787e315
4 changed files with 61 additions and 6 deletions

View File

@ -99,7 +99,7 @@ int Socket::ExceptionEventHandler(EventArgs::Ptr ea)
if (opt != 0) {
SocketErrorEventArgs::Ptr ea = make_shared<SocketErrorEventArgs>();
ea->Code = opt;
ea->Message = FormatErrorCode(opt);
ea->Message = FormatErrorCode(ea->Code);
OnError(ea);
Close();

View File

@ -19,6 +19,7 @@ private:
int ExceptionEventHandler(EventArgs::Ptr ea);
protected:
string FormatErrorCode(int errorCode);
protected:

View File

@ -37,11 +37,22 @@ void TCPClient::Connect(const string& hostname, unsigned short port)
int rc = connect(GetFD(), (sockaddr *)&sin, sizeof(sin));
#ifdef _WIN32
if (rc < 0 && WSAGetLastError() != WSAEWOULDBLOCK)
if (rc < 0 && WSAGetLastError() != WSAEWOULDBLOCK) {
#else /* _WIN32 */
if (rc < 0 && errno != EINPROGRESS)
if (rc < 0 && errno != EINPROGRESS) {
#endif /* _WIN32 */
SocketErrorEventArgs::Ptr ea = make_shared<SocketErrorEventArgs>();
#ifdef _WIN32
ea->Code = WSAGetLastError();
#else /* _WIN32 */
ea->Code = errno;
#endif /* _WIN32 */
ea->Message = FormatErrorCode(ea->Code);
OnError(ea);
Close();
}
m_PeerHost = hostname;
m_PeerPort = port;
@ -84,6 +95,18 @@ int TCPClient::ReadableEventHandler(EventArgs::Ptr ea)
return 0;
if (rc <= 0) {
if (rc < 0) {
SocketErrorEventArgs::Ptr ea = make_shared<SocketErrorEventArgs>();
#ifdef _WIN32
ea->Code = WSAGetLastError();
#else /* _WIN32 */
ea->Code = errno;
#endif /* _WIN32 */
ea->Message = FormatErrorCode(ea->Code);
OnError(ea);
}
Close();
return 0;
}
@ -104,6 +127,18 @@ int TCPClient::WritableEventHandler(EventArgs::Ptr ea)
rc = send(GetFD(), (const char *)m_SendQueue->GetReadBuffer(), m_SendQueue->GetSize(), 0);
if (rc <= 0) {
if (rc < 0) {
SocketErrorEventArgs::Ptr ea = make_shared<SocketErrorEventArgs>();
#ifdef _WIN32
ea->Code = WSAGetLastError();
#else /* _WIN32 */
ea->Code = errno;
#endif /* _WIN32 */
ea->Message = FormatErrorCode(ea->Code);
OnError(ea);
}
Close();
return 0;
}

View File

@ -8,8 +8,16 @@ void TCPSocket::MakeSocket(void)
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == INVALID_SOCKET)
throw exception(/*"socket() failed."*/);
if (fd == INVALID_SOCKET) {
SocketErrorEventArgs::Ptr ea = make_shared<SocketErrorEventArgs>();
#ifdef _WIN32
ea->Code = WSAGetLastError();
#else /* _WIN32 */
ea->Code = errno;
#endif /* _WIN32 */
ea->Message = FormatErrorCode(ea->Code);
OnError(ea);
}
SetFD(fd);
}
@ -30,6 +38,17 @@ void TCPSocket::Bind(const char *hostname, unsigned short port)
int rc = ::bind(GetFD(), (sockaddr *)&sin, sizeof(sin));
if (rc < 0)
if (rc < 0) {
SocketErrorEventArgs::Ptr ea = make_shared<SocketErrorEventArgs>();
#ifdef _WIN32
ea->Code = WSAGetLastError();
#else /* _WIN32 */
ea->Code = errno;
#endif /* _WIN32 */
ea->Message = FormatErrorCode(ea->Code);
OnError(ea);
Close();
}
}