// NFSocket class implementation // HttpSocket class implementation // Foota Software, 6 Jun. 2004 // // cl ws2_32.lib /GX #include #include "nfsocket.h" using namespace std; // NFSocket class NFSocket::NFSocket() { Init(); } NFSocket::~NFSocket() { Close(); Term(); // cerr << "termination" << endl; } int NFSocket::Init() { int ret = ::WSAStartup(2, &m_wsadata); if (ret != 0) cerr << "WinSock initilization error: " << ret << endl; return ret; } int NFSocket::Term() { return ::WSACleanup(); } int NFSocket::Bind(const struct sockaddr *addr, int namelen) { int ret = ::bind(m_socket, addr, namelen); if (ret == SOCKET_ERROR) cerr << "Bind error: " << ::WSAGetLastError() << endl; return ret; } int NFSocket::Listen(int backlog) { int ret = ::listen(m_socket, backlog); if (ret == SOCKET_ERROR) cerr << "Listen error: " << ::WSAGetLastError() << endl; return ret; } int NFSocket::Accept(struct sockaddr *addr, int *addrlen) { m_socket_client = ::accept(m_socket, addr, addrlen); if (m_socket_client == INVALID_SOCKET) { cerr << "Accept error: " << ::WSAGetLastError() << endl; return -1; } return 0; } int NFSocket::Connect(const struct sockaddr *name, int namelen) { int ret = ::connect(m_socket, name, namelen); if (ret == SOCKET_ERROR) cerr << "Connect error: " << ::WSAGetLastError() << endl; return ret; } int NFSocket::Open(int af, int type, int protocol) { m_socket = ::socket(af, type, protocol); if (m_socket == INVALID_SOCKET) { cerr << "WinSock socket error: " << ::WSAGetLastError() << endl; return -1; } return 0; } int NFSocket::Close() { return ::closesocket(m_socket); } int NFSocket::Shutdown(int how) { return ::shutdown(m_socket, how); } int NFSocket::Send(const char *buf, int len, int flags) { int size = ::send(m_socket, buf, len, flags); if (size == SOCKET_ERROR) cerr << "send error: " << ::WSAGetLastError() << endl; return size; } int NFSocket::Recv(char *buf, int len, int flags) { int size = ::recv(m_socket, buf, len, flags); if (size == SOCKET_ERROR) cerr << "recv error: " << ::WSAGetLastError() << endl; return size; } // HttpSocket class HttpSocket::HttpSocket() { Init(); } HttpSocket::~HttpSocket() { } int HttpSocket::Init() { int ret = NFSocket::Init(); Open(AF_INET, SOCK_STREAM, 0); return ret; } int HttpSocket::Term() { NFSocket::Close(); return NFSocket::Term(); } int HttpSocket::Connect(string servername) { HOSTENT *host = ::gethostbyname(servername.data()); if (host == NULL) { cerr << "gethostbyname error: " << ::WSAGetLastError() << endl; return -1; } IN_ADDR in_addr = *((IN_ADDR*)*host->h_addr_list); SOCKADDR_IN sockaddr_in; ::memset(&sockaddr_in, 0, sizeof(sockaddr_in)); sockaddr_in.sin_family = AF_INET; sockaddr_in.sin_port = ::htons(80); sockaddr_in.sin_addr = in_addr; return NFSocket::Connect((SOCKADDR*)&sockaddr_in, sizeof(sockaddr_in)); } int HttpSocket::Shutdown() { return NFSocket::Shutdown(SD_BOTH); }