Advertisement
Guest User

Server

a guest
Nov 10th, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. #include <WinSock2.h>
  5. #include <WS2tcpip.h>
  6. #include <stdio.h>
  7.  
  8. using namespace std;
  9.  
  10. #pragma comment(lib, "Ws2_32.lib")
  11.  
  12.  
  13. #define PORT_NUMBER 1337
  14. #define BUFFER_LENGTH 500
  15.  
  16.  
  17. int ShowError();
  18. void SendMessageToClient(SOCKET soc, char* msg);
  19.  
  20. int main()
  21. {
  22.  
  23.     WSADATA wsaData;
  24.  
  25.     int Result;
  26.  
  27.     Result = WSAStartup(MAKEWORD(2, 2), &wsaData);
  28.  
  29.     if (Result != 0)
  30.     {
  31.         WSACleanup();
  32.         return ShowError();
  33.     }
  34.  
  35.     SOCKET ListenSocket = INVALID_SOCKET;
  36.  
  37.     ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  38.  
  39.     if (ListenSocket == INVALID_SOCKET)
  40.     {
  41.         WSACleanup();
  42.         return ShowError();
  43.     }
  44.  
  45.     SOCKADDR_IN ServerInfo;
  46.  
  47.     ServerInfo.sin_port = htons(PORT_NUMBER);
  48.     ServerInfo.sin_family = AF_INET;
  49.     ServerInfo.sin_addr.s_addr = ADDR_ANY;
  50.    
  51.     //bind socket
  52.  
  53.     Result = bind(ListenSocket, (SOCKADDR*)&ServerInfo, sizeof(ServerInfo));
  54.  
  55.     if (Result == SOCKET_ERROR)
  56.     {
  57.         WSACleanup();
  58.         return ShowError();
  59.     }
  60.  
  61.     listen(ListenSocket, 1); //only waiting for 1 client
  62.  
  63.     SOCKET tempSock = INVALID_SOCKET;
  64.  
  65.     while (tempSock == INVALID_SOCKET)
  66.     {
  67.         cout << "Waiting for incoming connections..\n";
  68.  
  69.         tempSock = accept(ListenSocket, 0, 0);
  70.     }
  71.  
  72.  
  73.     cout << "\nClient Connected!\n";
  74.  
  75.  
  76.     SendMessageToClient(tempSock, "Test message\n");
  77.     Sleep(10);
  78.     SendMessageToClient(tempSock, "Another message!\n");
  79.    
  80.     shutdown(ListenSocket, SD_SEND);
  81.     closesocket(ListenSocket);
  82.  
  83.     WSACleanup();
  84.  
  85.     system("PAUSE > NUL");
  86.  
  87.     return 0;
  88. }
  89.  
  90.  
  91. void SendMessageToClient(SOCKET soc, char* msg)
  92. {
  93.        
  94.     int bSend = send(soc, msg, (int)strlen(msg), 0);
  95.  
  96.     printf("\n\nBytes Sent: %d\n\n", bSend);
  97. }
  98.  
  99. int ShowError()
  100. {
  101.     MessageBox(NULL, "An error occured.", 0, 0);
  102.     return 1;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement