Endil

cn-lab1-client

Sep 6th, 2015
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. // CN-lab1-client.cpp: определяет точку входа для консольного приложения.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <winsock2.h>
  7. #include <string>
  8. #include <thread>
  9. #include <condition_variable>
  10.  
  11. #pragma comment(lib, "ws2_32.lib")
  12.  
  13. using namespace std;
  14.  
  15. mutex m;
  16. condition_variable cvar;
  17. bool cvar_backup;
  18.  
  19. int input(SOCKET sock) {
  20.     string s;
  21.     while (true) {
  22.         cin >> s;
  23.         if (s == "exit") {
  24.             send(sock, "&close", sizeof("&close"), 0);
  25.             cvar.notify_one();
  26.             cvar_backup = true;
  27.             return 1;
  28.         }
  29.         send(sock, s.c_str(), s.length(), 0);
  30.     }
  31.     return 0;
  32. }
  33.  
  34. int receive(SOCKET sock) {
  35.     while (true) {
  36.         char recv_buff[1024];
  37.         int len = recv(sock, &recv_buff[0], sizeof(recv_buff), 0);
  38.         if (len == -1)
  39.             return 1;
  40.         recv_buff[len] = '\0';
  41.         string ans = recv_buff;
  42.         if (ans == "&stop") {
  43.             cout << "Server was stopped. Type \"exit\" to exit." << endl;
  44.             return 2;
  45.         }
  46.         if (ans == "0") cout << "not palindrome" << endl;
  47.         else cout << "palindrome" << endl;
  48.     }
  49.     return 0;
  50. }
  51.  
  52. int _tmain(int argc, _TCHAR* argv[])
  53. {
  54.     WSAData wsadata;
  55.     WSAStartup(0x0202, &wsadata);
  56.     SOCKET sock;
  57.     sock = socket(AF_INET, SOCK_STREAM, 0);
  58.     sockaddr_in server_addr;
  59.     server_addr.sin_family = AF_INET;
  60.     server_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
  61.     server_addr.sin_port = htons(5001);
  62.     connect(sock, (sockaddr *) &server_addr, sizeof(server_addr));
  63.     thread listen(receive, ref(sock));
  64.     thread input(input, ref(sock));
  65.     unique_lock<mutex> locked(m);
  66.     cvar.wait(locked, [] {return cvar_backup; });
  67.     closesocket(sock);
  68.     if (input.joinable())
  69.         input.join();
  70.     if (listen.joinable())
  71.         listen.join();
  72.     WSACleanup();
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment