/////////////////////////////////////////////////////////////////////// // basicServer.cpp - demonstrate operation of socket server // // // // Jim Fawcett, CSE691 - SW Modeling & Analysis, Fall 2000 // /////////////////////////////////////////////////////////////////////// #include #include #include using namespace std; int main() { cout << "\n Socket Server Demonstration " << "\n =============================\n"; ///////////////////////////////////////////////////////////////////// // load version 1.1 of winsock dll WORD wVersionRequested = MAKEWORD(1,1); // requesting version 1.1 WSAData wData; // startup data filled // by WSAStartup int err = WSAStartup(wVersionRequested, &wData); if(err == SOCKET_ERROR) { int errType = WSAGetLastError(); cout << "\n initialization error type: " << errType << "\n\n"; return errType; } /////////////////////////////////////////////////////////////////// // create TCP/IP socket object to listen for connection requests SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /////////////////////////////////////////////////////////////////// // bind listner socket to specific port and network interface int port = 2048; SOCKADDR_IN tcpAddr; tcpAddr.sin_family = AF_INET; // TCP/IP tcpAddr.sin_port = htons(port); // listening port tcpAddr.sin_addr.s_addr = INADDR_ANY; // listen over every network interface err = bind(listener, (SOCKADDR*)&tcpAddr, sizeof(tcpAddr)); if(err == SOCKET_ERROR) { int errType = WSAGetLastError(); cout << "\n initialization error type: " << errType << "\n\n"; return errType; } // /////////////////////////////////////////////////////////////////// // listen for incoming connection requests int backLog = 1; // backlog is one since we will err = listen(listener, backLog); // only listen for one client if(err == SOCKET_ERROR) { int errType = WSAGetLastError(); cout << "\n initialization error type: " << errType << "\n\n"; return errType; } cout << "\n waiting for incoming requests"; /////////////////////////////////////////////////////////////////// // block until a connection is established int size = sizeof(tcpAddr); SOCKET toClient = accept(listener, (SOCKADDR*)&tcpAddr, &size); cout << "\n established connection"; cout << "\n Received Data:"; /////////////////////////////////////////////////////////////////// // got connection so read transferred data string save; const int bufSize = 16; char buffer[bufSize]; int bytes, count=0; do { bytes = recv(toClient,buffer,bufSize-1,0); buffer[bytes] = '\0'; save += buffer; cout << "\n block " << ++count << ": " << save.c_str(); } while(bytes != 0 && bytes != SOCKET_ERROR); cout << endl; if(bytes == SOCKET_ERROR) { int errType = WSAGetLastError(); cout << "\n receive error type: " << errType << "\n\n"; return errType; } cout << "\n"; /////////////////////////////////////////////////////////////////// // close down gracefully shutdown(toClient,SD_RECEIVE); closesocket(toClient); closesocket(listener); WSACleanup(); return 0; }