Created
October 19, 2015 06:20
-
-
Save tensaix2j/609e9b6ee9e09d7e09ff to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <sys/select.h> | |
#include <sys/time.h> | |
#include <vector> | |
#include <error.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
using namespace std; | |
//----------------------------------------- | |
int createServer_FD( int portno ) { | |
int sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd < 0) { | |
perror("ERROR opening socket"); | |
} | |
struct sockaddr_in serv_addr; | |
bzero((char *) &serv_addr, sizeof(serv_addr)); | |
serv_addr.sin_family = AF_INET; | |
serv_addr.sin_addr.s_addr = INADDR_ANY; | |
serv_addr.sin_port = htons(portno); | |
if ( bind( sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { | |
perror("ERROR on binding"); | |
} | |
listen(sockfd,5); | |
return sockfd; | |
} | |
//--------------------------------------- | |
int main() { | |
fd_set readfds; | |
struct timeval tmTimeout; | |
tmTimeout.tv_sec = 0; | |
tmTimeout.tv_usec = 500000; | |
char buffer[1024]; | |
int server_fd = createServer_FD(10000); | |
vector <int> client_list; | |
printf("Sock server fd: %d ready, Entering Loop...\n", server_fd ); | |
for (;;) { | |
FD_ZERO(&readfds); | |
FD_SET( server_fd , &readfds); | |
for ( int i = 0 ; i < client_list.size() ; i++ ) { | |
FD_SET( client_list[i] , &readfds); | |
} | |
int readsocks = select( server_fd + 1 + client_list.size() , &readfds, (fd_set*)0, (fd_set*)0, &tmTimeout); | |
if ( readsocks == -1 ) { | |
perror("Socket Error"); | |
} | |
if ( readsocks == 0) { | |
/* Nothing ready to read, just show that | |
we're alive */ | |
} else { | |
// The sock server is in one of the ISSET in ReadSet | |
// This means it receives some connection request. | |
if ( FD_ISSET( server_fd, &readfds )) { | |
// Accept the client's connection request | |
printf( "Incoming Connection...\n"); | |
int connection = accept( server_fd, NULL, NULL); | |
if (connection == -1) { | |
perror("Accept error: Invalid socket!"); | |
} else { | |
printf("Connection accepted. Client fd %d\n", connection); | |
client_list.push_back( connection ); | |
} | |
} | |
for ( int i = 0 ; i < client_list.size() ; i++ ) { | |
if ( FD_ISSET( client_list[i] , &readfds ) ) { | |
// If it is , read and print | |
int n = recv( client_list[i], buffer, 1024, 0 ); | |
buffer[n] = 0; | |
printf("Received: %s", buffer) ; | |
} | |
} | |
} | |
//svc_getreqset( &readfds ); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment