1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| #include <iostream> #include <cstdio> #include <Winsock2.h> #include <string>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
#define xPort 8000 #define xIP "127.0.0.1"
int main() { const int xBUF_SIZE = 64; WSADATA wsd; SOCKET xServer; SOCKET xClient; SOCKADDR_IN xaddrServ; char string[xBUF_SIZE]; char sendinput[xBUF_SIZE]; int retVal;
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) { cout << "WSAStartup failed!" << endl; return 1; } xServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == xServer) { cout << "socket failed" << endl; WSACleanup(); return -1; } xaddrServ.sin_family = AF_INET; xaddrServ.sin_port = htons(xPort); xaddrServ.sin_addr.s_addr = INADDR_ANY;
retVal = bind(xServer, (SOCKADDR*)&xaddrServ, sizeof(SOCKADDR_IN)); if (SOCKET_ERROR == retVal) { cout << "bind failed" << endl; closesocket(xServer); WSACleanup(); return -1; }
retVal = listen(xServer, 1); if (SOCKET_ERROR == retVal) { cout << "listen failed" << endl; closesocket(xServer); WSACleanup(); return -1; }
sockaddr_in addrClient; int addrClientLen = sizeof(addrClient); xClient = accept(xServer, (sockaddr FAR*) & addrClient, &addrClientLen); if (INVALID_SOCKET == xClient) { cout << "accept failed" << endl; closesocket(xServer); WSACleanup(); return -1; }
while (true) { memset(sendinput, 0, xBUF_SIZE); recv(xClient,sendinput,xBUF_SIZE,0); cout << sendinput; memset(string,0,xBUF_SIZE); strcpy(string, "good :)"); send(xClient,string,xBUF_SIZE,0); }
closesocket(xServer); closesocket(xClient); WSACleanup();
return 0;
}
|