int TcpServer::start() { for (;;) /* Run forever */ { /* Set the size of the result-value parameter */ int clientLen = sizeof(ServerAddr); /* Wait for a Server to connect */ if ((client_sock = accept(sock, (struct sockaddr *)&ClientAddr, &clientLen)) == INVALID_SOCKET) { SysLogger::inst()->err("accept error"); return -1; } /* Create a Thread for this new connection and run*/ TcpThread * pt = new TcpThread(client_sock); pt->start(); } return 0; }
int main(void){ WSADATA wsadata; try{ if (WSAStartup(0x0202, &wsadata) != 0){ cout << "Error in starting WSAStartup()\n"; } else{ buffer = "WSAStartup was suuccessful\n"; WriteFile(test, buffer, sizeof(buffer), &dwtest, NULL); } //Display info of local host gethostname(localhost, 20); cout << "ftpd_tcp starting at host: [" << localhost << "]" << endl << "waiting to be contacted for transferring files..." << endl; if ((hp = gethostbyname(localhost)) == NULL) { cout << "gethostbyname() cannot get local host info?" << WSAGetLastError() << endl; exit(1); } //Create the server socket if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) throw "can't initialize socket"; //Fill-in Server Port and Address info. sa.sin_family = AF_INET; sa.sin_port = htons(port); sa.sin_addr.s_addr = htonl(INADDR_ANY); //Bind the server port if (bind(s, (LPSOCKADDR)&sa, sizeof(sa)) == SOCKET_ERROR) throw "can't bind the socket"; //Successfull bind, now listen for client requests. if (listen(s, 10) == SOCKET_ERROR) throw "couldn't set up listen on socket"; FD_ZERO(&readfds); while (1) { FD_SET(s, &readfds); //always check the listener if (!(outfds = select(infds, &readfds, NULL, NULL, tp))) {} else if (outfds == SOCKET_ERROR) throw "failure in Select"; else if (FD_ISSET(s, &readfds)) cout << "got a connection request" << endl; //Found a connection request, try to accept. if ((s1 = accept(s, &ca.generic, &calen)) == INVALID_SOCKET) throw "Couldn't accept connection\n"; //Start a new thread when a client connection is received TcpThread * t = new TcpThread(s1); t->start(); } } //Display needed error message. catch (char* str) { cerr << str << WSAGetLastError() << endl; } //close server socket closesocket(s); /* When done uninstall winsock.dll (WSACleanup()) and exit */ WSACleanup(); return 0; }