Advertisement
Panakotta00

Discord_Client.cpp

Sep 12th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #pragma warning(disable:4503)
  2.  
  3. #include "Discord_Client.h"
  4.  
  5. static const int MAX_LINE = 1024;
  6. int PORT;
  7. char *HOST;
  8.  
  9. #ifdef _WIN32
  10. SOCKET sockfd;
  11. #else
  12. pthread_t thread;
  13. int sockfd;
  14. #endif
  15.  
  16. Discord_Client::Discord_Client(int PORT, char *HOST) {
  17.     this->PORT = PORT;
  18.     this->HOST = HOST;
  19. }
  20.  
  21. Discord_Client::~Discord_Client() {
  22.     discord_disconnect();
  23. }
  24.  
  25. void Discord_Client::discord_connect() {
  26.     #ifdef _WIN32
  27.     WSADATA wsa;
  28.     if (WSAStartup(MAKEWORD(2, 0), &wsa) != 0) exit(1);
  29.     #endif
  30.    
  31.     sockfd = socket(AF_INET, SOCK_STREAM, 0);
  32.  
  33.     if (static_cast<int>(sockfd) < 0) {
  34.         perror("socket()");
  35.         discord_disconnect();
  36.         exit(1);
  37.     }
  38.     hostent *hp = gethostbyname(HOST);
  39.     if (!hp) {
  40.         cerr << "gethostbyname()" << endl;
  41.         discord_disconnect();
  42.         exit(1);
  43.     }
  44.     sockaddr_in sin;
  45.     memset((char*)&sin, 0, sizeof(sin));
  46.     sin.sin_family = AF_INET;
  47.     memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
  48.     sin.sin_port = htons(PORT);
  49.     memset(&(sin.sin_zero), 0, 8 * sizeof(char));
  50.     if (connect(sockfd, (sockaddr*)&sin, sizeof(sin)) == -1) {
  51.         perror("connect()");
  52.         discord_disconnect();
  53.         exit(1);
  54.     }
  55. }
  56.  
  57. void Discord_Client::discord_disconnect() {
  58.     #ifdef _WIN32
  59.     closesocket(sockfd);
  60.     WSACleanup();
  61.     #else
  62.     close(sockfd);
  63.     #endif
  64. }
  65.  
  66. string Discord_Client::discord_get(string msg) {
  67.     discord_send(("GET " + msg).c_str());
  68.     char buffer[MAX_LINE + 1] = { 0 };
  69.     if (recv(sockfd, buffer, MAX_LINE*sizeof(char), 0)<0) {
  70.         cout << buffer;
  71.         perror("recv()");
  72.         discord_disconnect();
  73.         exit(1);
  74.     }
  75.     cout << buffer;
  76.     return (string)buffer;
  77. }
  78.  
  79. void Discord_Client::discord_send(const char *msg) {
  80.     send(sockfd, msg, strlen(msg), 0);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement