#include #include #include #include #include #include #include #include #include #include #include void SendMsg(char* msg, int desc); int main (int argc, char** argv) { if (argc != 4) { cout << "recvqS \n"; cout << "\twhere socktype: \n\t\t1 -> SOCK_STREAM\n\t\t2 -> SOCK_CLUSTER\n"; cout << "\tThe starting port is ther port to which the first client connects, the nth client connects " << " to +(n-1)\n"; return 1; } int socktype = atoi(argv[1]); if ((socktype <= 0) || (socktype > 2)) { cout << "Socktype must be 1 for SOCK_STREAM or 2 for SOCK_CLUSTER\n"; return 1; } int sockDeclVal = 0; switch(socktype) { case 1: sockDeclVal = SOCK_STREAM; break; case 2: sockDeclVal = SOCK_CLUSTER; break; } char* machineName = argv[2]; int port = atoi(argv[3]); int usecs = 0; int secs = 0; int desc; int newDesc; struct hostent* host = gethostbyname(machineName); struct sockaddr_in sockStruct; sockStruct.sin_family = AF_INET; sockStruct.sin_port = port; sockStruct.sin_addr.s_addr = inet_addr(machineName); desc = socket(PF_INET, sockDeclVal, 0); //0->ip if (desc == -1) { cout << "Error setting protocol\n"; return 1; } if (bind(desc, (const sockaddr*)&sockStruct, sizeof(sockStruct)) == -1) { cout << "Error binding client, " << strerror(errno) << "\n"; return 1; } if (listen(desc, 0) == -1) { cout << "Error listening\n"; return 1; } struct sockaddr_in inSockStruct; socklen_t size; newDesc = accept(desc, (sockaddr*)&inSockStruct, &size); if (newDesc == -1) { cout << "Error accepting connection\n" ; return 1; } char msg[20]; strcpy(msg, "This is the message"); for (int i=0; i < 3000; i++) { SendMsg(msg, newDesc); } //let the client disconnect first cout << "The server has completed, it safe it continue the client. Press enter once the client is done"; cout.flush(); cin.getline(msg, 20); close(newDesc); close(desc); return 0; }; void SendMsg(char* msg, int desc) { int len = strlen(msg)+1; int sent; char msgLenStr[10]; sprintf(msgLenStr, "%d", len); if (sent = send(desc, (const void*)msgLenStr, 2, MSG_WAITALL) != 2) { cout << "Unable to send size of next msg\n"; exit(1); } if (sent = send(desc, (const void*) msg, len, MSG_WAITALL ) != len) { cout << "Wanted to send " << len << ", but only sent " << sent << "\n"; exit(1); } }