Advertisement
AntonioVillanueva

Client Basic Socket

Sep 23rd, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <cstring>
  2. #include <iostream>
  3. #include <netinet/in.h>
  4. #include <sys/socket.h>
  5. #include <unistd.h>
  6. #include <string>
  7. #include <arpa/inet.h>
  8.  
  9. #define IP "127.0.0.1"
  10. #define PORT 3310
  11. #define BUFFER_SIZE 1024
  12.  
  13. using namespace std;
  14.  
  15. int main()
  16. {
  17.  
  18.     // Creating socket
  19.     int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
  20.     if (clientSocket == -1) {
  21.         cerr << "Failed to create socket" << endl;
  22.         return 1;
  23.     }
  24.  
  25.     // Specifying server address
  26.     sockaddr_in serverAddress;
  27.     serverAddress.sin_family = AF_INET;//IPV4
  28.     serverAddress.sin_port = htons(PORT);
  29.     serverAddress.sin_addr.s_addr = inet_addr(IP);
  30.  
  31.     // Sending connection request
  32.     if (connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == -1) {
  33.         cerr << "Connection failed to " << IP<<":"<<PORT<< endl;
  34.         close(clientSocket);
  35.         return 1;
  36.     }
  37.  
  38.     cout << "Connected to server" <<IP<<":"<<PORT<< endl;
  39.  
  40.     // Sending data
  41.     const char* message = "PING\n";
  42.     if (send(clientSocket, message, strlen(message), 0) == -1) {
  43.         cerr << "Failed to send message" << endl;
  44.         close(clientSocket);
  45.         return 1;
  46.     }
  47.  
  48.    // cout << "Message sent: " << message<<end;
  49.  
  50.     // Receiving response
  51.     char buffer[BUFFER_SIZE] = {0};
  52.     int bytesReceived = recv(clientSocket, buffer, BUFFER_SIZE - 1, 0);
  53.     if (bytesReceived == -1) {
  54.         cerr << "Failed to receive response" << endl;
  55.     } else if (bytesReceived == 0) {
  56.         cout << "Server closed the connection" << endl;
  57.     } else {
  58.         cout <<"Response received: " << buffer<< " , Bytes Rx :" << bytesReceived<<endl;
  59.     }
  60.  
  61.     // Closing socket
  62.     close(clientSocket);
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement