Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <WS2tcpip.h>
  4. #pragma comment(lib, "ws2_32.lib")
  5.  
  6. using namespace std;
  7.  
  8. void main()
  9. {
  10.     string ipAddress = "198.72.227.45";         // IP Address of the server
  11.     int port = 54000;                       // Listening port # on the server
  12.  
  13.     // Initialize WinSock
  14.     WSAData data;
  15.     WORD ver = MAKEWORD(2, 2);
  16.     int wsResult = WSAStartup(ver, &data);
  17.     if (wsResult != 0)
  18.     {
  19.         cerr << "Can't start Winsock, Err #" << wsResult << endl;
  20.         system("PAUSE");
  21.         return;
  22.     }
  23.  
  24.     // Create socket
  25.     SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
  26.     if (sock == INVALID_SOCKET)
  27.     {
  28.         cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
  29.         WSACleanup();
  30.         system("PAUSE");
  31.         return;
  32.     }
  33.  
  34.     // Fill in a hint structure
  35.     sockaddr_in hint;
  36.     hint.sin_family = AF_INET;
  37.     hint.sin_port = htons(port);
  38.     inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);
  39.  
  40.     // Connect to server
  41.     int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
  42.     if (connResult == SOCKET_ERROR)
  43.     {
  44.         cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
  45.         closesocket(sock);
  46.         WSACleanup();
  47.         system("PAUSE");
  48.         return;
  49.     }
  50.  
  51.     // Do-while loop to send and receive data
  52.     char buf[4096];
  53.     string userInput;
  54.  
  55.     do
  56.     {
  57.         // Prompt the user for some text
  58.         cout << "> ";
  59.         getline(cin, userInput);
  60.  
  61.         if (userInput.size() > 0)       // Make sure the user has typed in something
  62.         {
  63.             // Send the text
  64.             int sendResult = send(sock, userInput.c_str(), userInput.size() + 1, 0);
  65.             if (sendResult != SOCKET_ERROR)
  66.             {
  67.                 // Wait for response
  68.                 ZeroMemory(buf, 4096);
  69.                 int bytesReceived = recv(sock, buf, 4096, 0);
  70.                 if (bytesReceived > 0)
  71.                 {
  72.                     // Echo response to console
  73.                     cout << "SERVER> " << string(buf, 0, bytesReceived) << endl;
  74.                 }
  75.             }
  76.         }
  77.  
  78.     } while (userInput.size() > 0);
  79.  
  80.     // Gracefully close down everything
  81.     closesocket(sock);
  82.     WSACleanup();
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement