Skip to content

Instantly share code, notes, and snippets.

@shoxsz
Last active November 9, 2016 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoxsz/d6a0b035907ad32a8537dffacaa73ed2 to your computer and use it in GitHub Desktop.
Save shoxsz/d6a0b035907ad32a8537dffacaa73ed2 to your computer and use it in GitHub Desktop.
using select from berkeley socket API to make a client/server with timeout
/*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 <algorithm>
#include <winsock2.h>
int main(){
UINT fd, client;
struct sockaddr_in sock_addr, client_addr;
int client_addr_size = sizeof(struct sockaddr_in);
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;
}
sock_addr.sin_family = AF_INET;
sock_addr.sin_addr.s_addr = INADDR_ANY;
sock_addr.sin_port = htons(80);
memset(&(sock_addr.sin_zero), 0x00, sizeof(sock_addr.sin_zero));
if(bind(fd, (struct sockaddr*)&sock_addr, sizeof(sockaddr_in)) < 0){
std::cout << "binding error!\n";
return -1;
}
if(listen(fd, 1) < 0){
std::cout << "listen error!\n";
return -1;
}
FD_ZERO(&m_fdset);
FD_SET(fd, &m_fdset);
if(select(fd + 1, &m_fdset, NULL, NULL, &timeout) < 0){
std::cout << "select error!\n";
return -1;
}
if(FD_ISSET(fd, &m_fdset)){
if((client = accept(fd, (struct sockaddr*)&client_addr, &client_addr_size)) == INVALID_SOCKET){
std::cout << "accept error!\n";
return -1;
}else{
std::string sendme;
std::string str_addr(inet_ntoa(sock_addr.sin_addr));
std::cout << "new connection from: " << str_addr << std::endl;
std::cout << "write a message to send:\n";
std::cin >> sendme;
if(send(client, sendme.c_str(), std::min<unsigned int>(sendme.length(), 4096), 0) <= 0){
std::cout << "send error or connection finished!\n";
system("pause");
return -1;
}
}
}else{
std::cout << "No connections!\n";
}
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment