Note that there are some explanatory texts on larger screens.

plurals
  1. PO(C++) Sending JPG files over sockets
    text
    copied!<p>I am learning programming in C/C++ with sockets, and am trying to move a binary file from the server to the client. Here's what I have on the server side. </p> <pre><code>ifstream file(argv[1],ios::binary|ios::ate) size = new char[file.tellg()] memblock = new char[size] file.seekg(0,ios::beg); file.read(memblock,size); </code></pre> <p>After having read the contents of the binary file into memblock, I then transfer that across using the socket function read. </p> <pre><code>listen(sockd, 5); newsock=accept(sockfd, NULL, NULL); write(newsock, memblock, strlen(memblock)); delete[] memblock; </code></pre> <p>Meanwhile, on the client side </p> <pre><code>connect(sockfd, &amp;servaddr, sizeof(servaddr)); read(sockfd, buffer, size); ofstream output(argv[1], ios::binary); output.write(buffer, strlen(buffer)); output.close(); delete[] buffer </code></pre> <p>I understand there are some errors that could crop up, such as the file size could be bigger than the amount transmitted and therefore the file is not completely copied. This is just the first step of the program, so I will make the necessary modifications for transferring in chunks later. </p> <p>Now the source code itself is 1kb (714 bytes to be precise). When I load it in the server program, it correctly reports strlen(buffer) to be 715. And when running the client, it correctly reports reading 715 bytes as well, and I get a nice output file identical to the original_source_code.cpp </p> <p>However, I have a 512 bytes jpg file. The server program reports strlen(buffer) to be 512 correctly, however, the client only reads in 4 bytes and stops. The amount of bytes read varies with different file formats, but it never really reads the complete buffer. However text files get transmitted through sockets without any issues. </p> <p>Any reasons why this is happening? I am not even able to do it within the same machine, as in run an instance of the server and ask the client instance to connect to 127.0.0.1. </p> <p>Any suggestions would be appreciated ! </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload