Advertisement
tuanln

File Client via Winsock (S->C)

Oct 5th, 2015
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. // FileClient.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include "stdio.h"
  6. #include "conio.h"
  7. #include "winsock2.h"
  8. #include "ws2tcpip.h"
  9.  
  10. SOCKET s;
  11. SOCKADDR_IN sAddr;
  12.  
  13. DWORD WINAPI ReceiverThread(LPVOID Param) {
  14.     char buf[1024];
  15.     int len;
  16.     while (true) {
  17.         len = recv(s, buf, 1024, 0);
  18.         if (len > 0) {
  19.             buf[len] = 0;
  20.             int size = atoi(buf);
  21.             if (size == 0) {
  22.                 printf("%s", buf);
  23.             }
  24.             else {
  25.                 FILE *fw = fopen("b.jpg", "wb");
  26.  
  27.                 int checksize = 0;
  28.                 char* buffer;
  29.                 buffer = (char*)malloc(size + 1);
  30.                 while (checksize < size) {
  31.                     int Received = recv(s, buffer, size, 0);
  32.                     int Written = fwrite(buffer, sizeof(char), Received, fw);
  33.                     checksize += Written;
  34.                     for (int i = 0; i < Written; i++) {
  35.                         if (buffer[i] == '\n') {
  36.                             checksize += 1;
  37.                         }
  38.                     }
  39.                 }
  40.                 fclose(fw);
  41.                 free(buffer);
  42.                 printf("complete");
  43.             }
  44.         }
  45.     }
  46.     return 0;
  47. }
  48.  
  49. int main()
  50. {
  51.     WSADATA wsadata;
  52.     int ret = WSAStartup(MAKEWORD(2, 2), &wsadata);
  53.  
  54.     s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  55.  
  56.     sAddr.sin_family = AF_INET;
  57.     sAddr.sin_port = htons(10008);
  58.     sAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  59.  
  60.     connect(s, (sockaddr*)&sAddr, sizeof(sAddr));
  61.    
  62.     char buf[1024];
  63.  
  64.     CreateThread(0, 0, ReceiverThread, 0, 0, 0);
  65.     while (true) {
  66.         fgets(buf, 1024, stdin);
  67.         send(s, buf, strlen(buf), 0);
  68.     }
  69.  
  70.     closesocket(s);
  71.     WSACleanup();
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement