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
|
#include "ConnectionHeader.h"
int Init()
{
for(int i = 0; i < 30; i++)
{
collection_sock[i] = 0;
}
for(int i = 0; i < DEFAULT_BUFLEN; i++)
{
recvBuffer[i] = 0;
}
ZeroMemory(&addInfo,sizeof(addInfo));
addInfo.ai_family = AF_INET;
addInfo.ai_protocol = IPPROTO_TCP;
addInfo.ai_socktype = SOCK_STREAM;
return 0;
}
int MakeConnection()
{
BOOL Mode = TRUE;
int modeLen = sizeof(Mode);
int addrSize = sizeof(clientAddress);
errn = WSAStartup(MAKEWORD(2,2),&wsadata);
if(errn == SOCKET_ERROR)
printf("Errore in WSAstartUp \n");
result = &addInfo;
errn = getaddrinfo(NULL,DEFAULT_PORT,&addInfo,&result);
if(errn != 0)
printf("Errore in getaddrinfo \n");
master_socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(master_socket == INVALID_SOCKET)
printf("Errore in socket func %d\n",WSAGetLastError());
errn = setsockopt(master_socket,SOL_SOCKET,SO_REUSEADDR,(char *)&Mode,modeLen);
if(errn == SOCKET_ERROR)
printf("Errore in setsockop %d\n",WSAGetLastError());
errn = bind(master_socket,result->ai_addr,result->ai_addrlen);
if(errn == SOCKET_ERROR)
printf("Errore in bind %d\n",WSAGetLastError());
errn = listen(master_socket,SOMAXCONN);
if(errn == SOCKET_ERROR)
printf("Errore in listen %d\n",WSAGetLastError());
return 0;
}
int _verifySocket()
{
while(true)
{
FD_ZERO(&fds);
FD_SET(master_socket,&fds);
for(int i = 1; i < 30; i++)
{
if(collection_sock[i] > 0)
FD_SET(collection_sock[i],&fds);
}
errn = select(master_socket +1,&fds,NULL,NULL,NULL);
if(errn == -1)
printf("Errore in select \n");
if(FD_ISSET(master_socket,&fds))
{
CLIENT = accept(master_socket,NULL,NULL);
if(CLIENT == -1)
printf("Errore in accept %d\n",WSAGetLastError());
FD_SET(CLIENT,&fds);
printf("\nNew connection from socket %d ip: %s\n",CLIENT,inet_ntoa(clientAddress.sin_addr));
Thread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)HandleRequest,(LPVOID)CLIENT,0,&threadId);
}
for(int i = 1; i < 30; i++)
{
if(collection_sock[i] = 0)
{
collection_sock[i] = CLIENT;
printf("Adding client in collection at position: %d/30\n",i);
break;
}
}
}
return 0;
}
// ----------------------------------------------------------------------------------------------------
DWORD WINAPI HandleRequest(){
do{
recvResult = recv(CLIENT,recvBuffer,sizeof(recvBuffer),NULL);
switch(recvResult)
{
case -1: printf("\nErrore in recv %d\n",WSAGetLastError()); return -1;
break;
default : printf("Receiving %d byte",recvResult); return 0; ExitThread(0);
}
}while(recvResult > 0);
}
|