Facebook
From Rahabul Islam, 1 Week ago, written in C++.
Embed
Download Paste or View Raw
Hits: 150
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstring>
  4. #include <arpa/inet.h>
  5. #include <unistd.h>
  6.  
  7. #define PORT 8080
  8. #define BUFFER_SIZE 1024
  9.  
  10. int main() {
  11.     // Create socket
  12.     int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
  13.     if (serverSocket == -1) {
  14.         std::cerr << "Error creating socket\n";
  15.         return -1;
  16.     }
  17.  
  18.     // Set up server address structure
  19.     sockaddr_in serverAddress{};
  20.     serverAddress.sin_family = AF_INET;
  21.     serverAddress.sin_addr.s_addr = INADDR_ANY;
  22.     serverAddress.sin_port = htons(PORT);
  23.  
  24.     // Bind the socket
  25.     if (bind(serverSocket, (struct sockaddr*)&serverAddress;, sizeof(serverAddress)) < 0) {
  26.         std::cerr << "Error binding socket\n";
  27.         return -1;
  28.     }
  29.  
  30.     // std::ifstream fileToSend("in.txt", std::ios::binary);
  31.  
  32.     std::cout << "Server listening on port " << PORT << "\n";
  33.     // Listen for incoming connections
  34.     if (listen(serverSocket, 3) < 0) {
  35.         std::cerr << "Error listening for connections\n";
  36.         return -1;
  37.     }
  38.  
  39.     while(true){
  40.    
  41.         // Accept a connection
  42.         int clientSocket = accept(serverSocket, nullptr, nullptr);
  43.         if (clientSocket < 0) {
  44.             std::cerr << "Error accepting connection\n";
  45.             return -1;
  46.         }
  47.    
  48.         // Open the file to send
  49.         std::ifstream fileToSend("binaryfile.bin", std::ios::binary);
  50.    
  51.         if (!fileToSend.is_open()) {
  52.             std::cerr << "Error opening file\n";
  53.             return -1;
  54.         }
  55.    
  56.         char buffer[BUFFER_SIZE];
  57.         while (!fileToSend.eof()) {
  58.             fileToSend.read(buffer, sizeof(buffer));
  59.             send(clientSocket, buffer, fileToSend.gcount(), 0);
  60.         }
  61.         fileToSend.close();
  62.  
  63.         std::cout << "File sent successfully\n";
  64.         close(clientSocket);
  65.     }
  66.  
  67.     // Close the file and sockets
  68.     // fileToSend.close();
  69.     // close(clientSocket);
  70.     close(serverSocket);
  71.  
  72.     // std::cout << "File sent successfully\n";
  73.  
  74.     return 0;
  75. }