/////////////////////////////////////////////////////////////////////// // basicClient.cpp - demonstrate operation of socket client // // // // Jim Fawcett, CSE691 - SW Modeling & Analysis, Fall 2000 // /////////////////////////////////////////////////////////////////////// #include #include #include "..\sockUtils\sockUtils.h" using namespace std; int main() { cout << "\n Socket Client 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 sysError errMsg; int err = WSAStartup(wVersionRequested, &wData); if(err == SOCKET_ERROR) { int errType = WSAGetLastError(); cout << "\n initialization error type: " << errType << "\n " << errMsg.getLastMsg().c_str() << "\n\n"; return errType; } /////////////////////////////////////////////////////////////////// // create TCP/IP socket object SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /////////////////////////////////////////////////////////////////// // connect to server on specified address and port // - note the IP address 127.0.0.1 refers to host machine int port = 2048; // user port struct hostent *serverHostent; serverHostent = gethostbyname("localhost"); SOCKADDR_IN tcpAddr; tcpAddr.sin_family = AF_INET; // TCP/IP tcpAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // host machine // tcpAddr.sin_addr.s_addr = inet_addr(serverHostent->h_addr_list[0]); // host machine tcpAddr.sin_port = htons(port); // server port err = connect(sock, (sockaddr*)&tcpAddr, sizeof(tcpAddr)); if(err == SOCKET_ERROR) { int errType = WSAGetLastError(); cout << "\n connection error type: " << errType << "\n " << errMsg.getLastMsg().c_str() << "\n\n"; return errType; } // /////////////////////////////////////////////////////////////////// // send data to server char *buffer = "Hello World via Socket Connection"; cout << "\n sending: \"" << buffer << "\""; int numBytesSent; // may not send whole buffer numBytesSent = send(sock, buffer, strlen(buffer), 0); if(numBytesSent != strlen(buffer)) cout << "\n-- not all bytes sent --"; buffer = " : Second Block of Data"; cout << "\n sending: \"" << buffer << "\"\n\n"; numBytesSent = send(sock, buffer, strlen(buffer), 0); if(numBytesSent != strlen(buffer)) cout << "\n-- not all bytes sent --"; if(numBytesSent == SOCKET_ERROR) { int errType = WSAGetLastError(); cout << "\n send error type: " << errType << "\n\n"; return errType; } /////////////////////////////////////////////////////////////////// // tell server we are shutting down shutdown(sock, SD_SEND); closesocket(sock); WSACleanup(); return 0; }