1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| int server::start()
{
if((socket_server = socket(AF_INET, SOCK_STREAM, 0)) < 0){
std::cout<<"Socket creation error !\n"<<std::endl;
return EXIT_FAILURE;
}
if(bind(socket_server,
(struct sockaddr*)&sockaddr_server,
server_len
) < 0){
std::cout<<"Socket bind error !\n"<<std::endl;
return EXIT_FAILURE;
}
if(listen(socket_server, 10) < 0){
std::cout<<"Socket listen error !\n"<<std::endl;
return EXIT_FAILURE;
}
while (1){
PSOCKET_GROUP socketGroup;
struct sockaddr_in sockaddIn;
unsigned int sockaddrLen;
pthread_t threadSender, threadReceiver;
sockaddrLen = sizeof(sockaddIn);
socketGroup = (PSOCKET_GROUP) malloc ( sizeof(SOCKET_GROUP) );
socketGroup->socketToClient = accept(socket_server,
(struct sockaddr *)&sockaddIn,
&sockaddrLen
);
socketGroup->threadContext = threadCount;
socketGroup->socketToServer=-1;
sem_init(&socketGroup->semaphore, 0, 0);
threadCount ++;
pthread_create(&threadReceiver,
NULL,
proxySendFunction,
( void* ) socketGroup
);
pthread_create(&threadSender,
NULL,
proxyReceiveFunction,
( void* ) socketGroup);
}
}
void* server::proxySendFunction( void* socketAdress )
{
BUFFER buff, host;
int port, socketToHost, len;
PSOCKET_GROUP sockG;
sockG = static_cast<PSOCKET_GROUP>(socketAdress);
buff = (BUFFER) malloc (MAX_RECEIVE*sizeof(char));
Connection* con = new Connection ();
while((len=con->receiveData( sockG->socketToClient,
buff )
)>0){
if ((int)sockG->socketToServer==-1){
std::cout<<"\nparsing name and port"<<std::endl;
std::cout<<"sending to server\n"<< buff <<std::endl;
host = HTTPParser::parseHostName( buff );
port = HTTPParser::parsePortNumber( buff );
sockG->socketToServer =con->sendData(host,
port,
buff,
len
);
sem_post(&sockG->semaphore);
}
else{
std::cout<<"\nsending .. to server\n"<< buff <<std::endl;
con->sendData(sockG->socketToServer,
buff,
len
);
}
}//fin while
pthread_exit(0);
}
void* server::proxyReceiveFunction( void* socketAdress )
{
Connection* con = new Connection();
BUFFER buff;
PSOCKET_GROUP sockG;
int len;
std::cout<<"thread 2 waiting for semaphore release"<<std::endl;
sockG = static_cast<PSOCKET_GROUP>(socketAdress);
sem_wait( &sockG->semaphore );
std::cout<<"thread2 released"<<std::endl;
buff = ( BUFFER ) malloc ( MAX_RECEIVE );
while((len=con->receiveData( sockG->socketToServer,
buff))>0){
std::cout<<"\nreceiving from server and sending to client :\n"<< buff <<std::endl;
con->sendData( sockG->socketToClient,
buff,
len);
}// fin while
pthread_exit(0);
} |
Partager