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
|
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR ){
printf("Error at WSAStartup()\n");
return;
}
// Create a socket.
SOCKET controlSocket;
controlSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( controlSocket == INVALID_SOCKET ) {
printf( "Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return;
}
// Bind the socket.
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY; //use local address
addr.sin_port = htons(SERVER_PORT);
if ( bind( controlSocket, (SOCKADDR*) &addr, sizeof(addr) ) == SOCKET_ERROR ) {
printf( "bind() failed.\n" );
closesocket(controlSocket);
WSACleanup();
return;
}
// Listen on the Socket.
if ( listen( controlSocket, MAX_PENDING ) == SOCKET_ERROR ){
printf( "Error listening on socket.\n");
closesocket(controlSocket);
WSACleanup();
return;
}
// Accept connections.
SOCKET s;
printf( "Waiting for a client to connect...\n" );
while(1){
s = accept( controlSocket, NULL, NULL );
if( s == SOCKET_ERROR){
printf("accept() error \n");
closesocket(controlSocket);
WSACleanup();
return;
}
printf( "Client Connected.\n");
// Send and receive data.
char buf[MAX_LINE];
int len = recv( s, buf, MAX_LINE, 0 );
buf[len] = 0;
int p = newClient(clientList,buf);
if(p>-1){
send( s, clientList[p].handle, strlen(clientList[p].handle), 0 );
}
else{
char *reject = "Too many clients connected at this time or there was an error! Sorry!";
send( s, reject, strlen(reject), 0);
}
closesocket(s);
|