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; 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); while((lReadSize = recv(lAcceptedSocket,lBuf,MaxLine,0)) > 0) { string lRecvStr(lBuf,lReadSize); long lNum1 = 0, lNum2 = 0; if (sscanf(lRecvStr.c_str(), "%ld%ld", &lNum1, &lNum2) == 2) { sprintf(lBuf,"%ld\n", lNum1+lNum2); } else sprintf(lBuf,"Input Error\n"); if ("close" == lRecvStr) { closesocket(lAcceptedSocket); return 0; } send(lAcceptedSocket,lBuf,strlen(lBuf),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; void StrClient(SOCKET &aSockfd) { string lStr; while (getline(cin, lStr) != NULL) { send(aSockfd,lStr.c_str(),lStr.size(),0); char lSendline[MaxLine]; int lReadSize = 0; if ( (lReadSize = recv(aSockfd,lSendline,MaxLine,0) ) == 0 ) { cerr << "sever terminated prematurely\n"; return ; } string lRecvStr(lSendline,lReadSize); cout << lRecvStr << 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; }