peterzig

[PWŚS] TCP Średnia

May 28th, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <winsock.h>
  3. #include <conio.h>
  4.  
  5. #pragma comment(lib,"ws2_32.lib")
  6. enum {ESC = 27, SPACE = 32};
  7.  
  8. void main()
  9. {
  10.     WSADATA wsadata;
  11.     if( WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
  12.     {
  13.         printf("WSAStartup failed with error: %d\n", WSAGetLastError());
  14.         _getch();
  15.         return;
  16.     }
  17.  
  18.     SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  19.     if (s == INVALID_SOCKET)
  20.     {
  21.         WSACleanup();
  22.         printf("Creating socket failed with error: %d\n", WSAGetLastError());
  23.         _getch();
  24.         return;
  25.     }
  26.     sockaddr_in serwer;
  27.     serwer.sin_family = AF_INET;
  28.     serwer.sin_port = htons(7708);
  29.     serwer.sin_addr.s_addr = inet_addr("127.1.0.0");
  30.  
  31.     while(true)
  32.     {
  33.         printf("Dowolny klawisz - kontynuowanie programu\nEsc - koniec programu\n\n");
  34.         int wybor = _getch();
  35.  
  36.         if( wybor = ESC)
  37.             break;
  38.  
  39.         if(connect(s, (sockaddr*) &serwer, sizeof(serwer)) < 0)
  40.         {
  41.             printf("Polaczenie z serweem nieudane!\n");
  42.             _getch();
  43.             continue;
  44.         }
  45.         send(s, "AVRGE", sizeof("AVRGE"), 0);
  46.  
  47.         while (true)
  48.         {
  49.             float liczba1, liczba2, srednia;
  50.             char kod = 0xDD;
  51.             int licznik = 0;
  52.  
  53.             recv(s, (char*)&liczba1, sizeof(float), 0);
  54.             recv(s, (char*)&liczba2, sizeof(float), 0);
  55.  
  56.             srednia = (liczba1 + liczba2) / 2;
  57.             send(s, (char*)&srednia, sizeof(float), 0);
  58.  
  59.             printf("Otrzymane liczby: %.2f i %.2f\nSrednia liczb: %.2f\n\n", liczba1, liczba2, srednia);
  60.             if (++licznik % 10 == 0)
  61.             {
  62.                 if (send(s, (char*)&kod, sizeof(char), 0) == SOCKET_ERROR)
  63.                     break;
  64.                 printf("Przesylanie kodu 0xDD\n\n");
  65.             }
  66.         }
  67.     }
  68.  
  69.     printf("Konczenie dzialania programu\n");
  70.     shutdown(s, 2);
  71.     closesocket(s);
  72.     WSACleanup();
  73.     getch();
  74. }
Add Comment
Please, Sign In to add comment