Last active
November 9, 2016 22:31
-
-
Save shoxsz/e9ff2bd5e99929361e57a4e43222e039 to your computer and use it in GitHub Desktop.
using select from berkeley socket API to make a client/server with timeout
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
/*This is for a stackoverflow answear: | |
http://pt.stackoverflow.com/questions/144150/como-implementar-timeout-no-recv-em-socket-h/164440#164440 | |
the code was compiled with mingw g++ using codeblocks, in order to compile this code you must link it to the ws2_32.lib on windows | |
*/ | |
#include <iostream> | |
#include <string> | |
#include <winsock2.h> | |
int main(){ | |
UINT fd; | |
const unsigned short port = 80; | |
const char host[] = {"127.0.0.1"}; | |
struct sockaddr_in server; | |
struct fd_set m_fdset; | |
struct timeval timeout = {10, 0}; | |
WSADATA wsaData; | |
if(WSAStartup(MAKEWORD(2, 2), &wsaData) < 0){ | |
std::cout << "wsastartup error!!" << std::endl; | |
return 0; | |
} | |
if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ | |
std::cout << "socket error!!" << std::endl; | |
return 0; | |
} | |
server.sin_family = AF_INET; | |
server.sin_addr.s_addr = inet_addr(host); | |
server.sin_port = htons(port); | |
memset(&(server.sin_zero), 0x00, sizeof(server.sin_zero)); | |
if(connect(fd, (struct sockaddr*)&server, sizeof(server)) < 0){ | |
std::cout << "connect error!!" << std::endl; | |
return -1; | |
} | |
FD_ZERO(&m_fdset); | |
FD_SET(fd, &m_fdset); | |
int r = select(fd + 1, &m_fdset, NULL, NULL, &timeout); | |
if(r == SOCKET_ERROR){ | |
std::cout << "select error!\n"; | |
return -1; | |
}else{ | |
if(FD_ISSET(fd, &m_fdset)){ | |
int read; | |
std::string buffer; | |
buffer.resize(4096); | |
if((read = recv(fd, (char*)buffer.data(), 4096, 0)) <= 0){ | |
std::cout << "recv error or connection finished!\n"; | |
return -1; | |
} | |
buffer.resize(read); | |
std::cout << "read " << read << " bytes from server:\n"; | |
std::cout << buffer << std::endl; | |
}else{ | |
std::cout << "TIMEOUT!" << std::endl; | |
} | |
} | |
closesocket(fd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment