Created
September 27, 2013 11:55
-
-
Save RklAlx/6727485 to your computer and use it in GitHub Desktop.
Socket Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CMyClient::CMyClient(const char* pIP, unsigned int port) | |
{ | |
m_Socket = INVALID_SOCKET; | |
_snprintf_s(this->m_IP,IP_SIZE,_TRUNCATE,pIP); | |
this->InitSockAddrIn(); | |
} | |
void CMyClient::InitSockAddrIn() | |
{ | |
this->m_SockAddrIn.sin_family = AF_INET; | |
this->m_SockAddrIn.sin_addr.s_addr = inet_addr(this->m_IP); | |
this->m_SockAddrIn.sin_port = htons(this->m_Port); | |
} | |
bool CMyClient::Connect() | |
{ | |
this->m_Socket = socket(AF_INET, SOCK_STREAM, 0); | |
if(m_Socket == INVALID_SOCKET) | |
{ | |
std::cout << "Connect: Failed to create socket" << std::endl; | |
return false; | |
} | |
if(!ConnectSocket()) | |
{ | |
this->Close(); | |
return false; | |
} | |
//TODO criar receiver e/ou sender | |
return true; | |
} | |
bool CMyClient::ConnectSocket() | |
{ | |
char error_msg[200]; | |
for(int i=0; i<m_MaxRetries; i++) | |
{ | |
if(i != 0) | |
Sleep(10000); | |
std::cout << "[Destination] Connecting..." << std::endl; | |
if(connect(m_Socket,(sockaddr*) &this->m_SockAddrIn,sizeof(this->m_SockAddrIn)) != SOCKET_ERROR) | |
{ | |
std::cout << "Socket connected" << std::endl; | |
return true; | |
} | |
std::cout << "Connect: (attempt " << i+1 << " of " << m_MaxRetries << " Failed to connect socket. Error: " << WSAGetLastError() << std::endl; | |
} | |
std::cout << "Connect - maximum connection attempts reached" << std::endl; | |
return false; | |
} | |
void Close() | |
{ | |
if(this->m_Socket != INVALID_SOCKET) | |
{ | |
if (closesocket(m_Socket) == SOCKET_ERROR) | |
std::cout << "Failed to close socket: " << WSAGetLastError() << std::endl; | |
this->m_Socket = INVALID_SOCKET; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <winsock2.h> | |
#include <ws2tcpip.h> | |
#include <windows.h> | |
#define IP_SIZE 30 | |
class SocketClient | |
{ | |
public: | |
SocketClient(const char* pIP, unsigned int port); | |
~SocketClient(); | |
private: | |
SOCKET m_Socket; | |
char m_IP[IP_SIZE]; | |
sockaddr_in m_SockAddrIn; | |
//-------- | |
void InitSockAddrIn(); | |
bool Connect(); | |
bool ConnectSocket(); | |
void Close(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment