server:
#include"WinSock2.h" #include "time.h" #include "stdio.h" #include <string> #include <iostream> #pragma comment(lib,"WS2_32") using namespace std; const int MaxLine = 1024; char lBuf[MaxLine]; short gPort = 9877; struct Args { long arg1; long arg2; }; struct Result { long sum; }; int main() { int lRet = 0; WSADATA lWsaData; if ((lRet = WSAStartup(MAKEWORD(2,2), &lWsaData)) != 0) { cout << "Error " << lRet << endl; return 0; } int lListen = 0, lConnfd = 0; SOCKADDR_IN lServAddr; lServAddr.sin_family = AF_INET; lServAddr.sin_addr.s_addr = htonl(INADDR_ANY); lServAddr.sin_port = htons(gPort); SOCKET lSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == lSocket) { cout << "INVALID_SOCKET" << endl; return 0; } bind(lSocket,(sockaddr*)(&lServAddr),sizeof(lServAddr)); listen(lSocket,5); while(true) { SOCKADDR_IN lClientAddr; int lLen = sizeof(lClientAddr); SOCKET lAcceptedSocket = accept(lSocket,(sockaddr*)&lClientAddr,&lLen); printf("Connection from %s, port %d\n",inet_ntoa(lClientAddr.sin_addr),ntohs(lClientAddr.sin_port)); int lReadSize = 0; int lSize = strlen(lBuf); Args lArgs; Result lResult; while((lReadSize = recv(lAcceptedSocket,(char*)(&lArgs),sizeof(lArgs),0)) > 0) { lResult.sum = lArgs.arg1 + lArgs.arg2; send(lAcceptedSocket,(char*)(&lResult),sizeof(lResult),0); } closesocket(lAcceptedSocket); } }
client:
#include<WinSock2.h> #include <iostream> #include <string> using namespace std; #pragma comment(lib, "WS2_32") short gPort = 9877; const int MaxLine = 1024; struct Args { long arg1; long arg2; }; struct Result { long sum; }; void StrClient(SOCKET &aSockfd) { string lStr; Args lArgs; Result lResult; while (getline(cin, lStr) != NULL) { if(sscanf(lStr.c_str(),"%ld%ld",&lArgs.arg1,&lArgs.arg2) != 2) { printf("Invalid Input"); continue; } send(aSockfd,(char*)(&lArgs),sizeof(lArgs),0); char lSendline[MaxLine]; int lReadSize = 0; if ( (lReadSize = recv(aSockfd,(char*)(&lResult),sizeof(lResult),0) ) == 0 ) { cerr << "sever terminated prematurely\n"; return ; } cout << lResult.sum << endl; } } int main() { int lRet = 0; WSADATA lWsaData; if ((lRet = WSAStartup(MAKEWORD(2,2), &lWsaData)) != 0) { cout << "Error " << lRet << endl; return 0; } SOCKADDR_IN lAddr; lAddr.sin_family = AF_INET; lAddr.sin_port = htons(gPort); int lNum = 0; int lReadTime = 0; SOCKET lSocket = socket(AF_INET, SOCK_STREAM, 0); if (INVALID_SOCKET == lSocket) { cout << "INVALID_SOCKET" << endl; return 0; } lAddr.sin_addr.s_addr = inet_addr("192.168.1.102"); if (connect(lSocket,(sockaddr*)(&lAddr),sizeof(lAddr)) < 0 ) { cout << "connect error" << endl; return 0; } StrClient(lSocket); return 0; }