I send a vector containing 120000 from my computer to a server by tcp/ip ssh tunnel. Every time, I send 250 values of type double and the sever send me back them to ensure that I have sent the data correctly. I use the function read() to recieve the data in the server. As we know, read() cannot always recieve all the 250 values (250*8=2000bytes) in one time. Thus, I use the function memcpy() to save the recieved data until it reach 2000 bytes. However, the memcpy only work one times.
For example, I send 250 values (2000bytes). The server recieves 1408 bytes in the 1st time. I use memcpy() to save these 1406 bytes into a array from the buffer. The server recieves 594 bytes in the 2nd time. I use memcpy() to save these 592 bytes into the same array from the buffer. However, I find the 2nd time, memcpy() does not work according to the value send back from server to my computer.
The code c++ in server has two objectives:
1. recieve the 250 data every times.
2. send them back every times.
#include <stdio.h>
#include <iostream>
#include<vector>
#include <math.h>
extern "C"
void useCUDA();
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;
int main()
{
vector<double> Y;
int lread = 250, nMu = 4, ltotal = 120000;
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_addr.sin_port = htons(54321);
connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
double* block_buffer_input;
block_buffer_input = new double[lread];
double* block_input;
block_input = new double[lread];
double* block_buffer_output;
block_buffer_output = new double[lread];
while (Y.size() < ltotal)
{
int nbyteread = 0;
int nbytereadtimes = 0;
while (nbyteread < 8 * lread)
{
nbytereadtimes = read(sock, reinterpret_cast<char*>(block_buffer_input), lread * sizeof(double));
memcpy(block_input + nbyteread, block_buffer_input, nbytereadtimes);
if (nbytereadtimes != 8 * lread && nbytereadtimes != 0)
cout << Y.size() << ": " << nbytereadtimes << " " << block_input + nbyteread <<endl;
nbyteread += nbytereadtimes;
}
Y.insert(Y.end(), &block_input[0], &block_input[lread]);
cout << Y.size() << ": " << nbyteread << endl;
int Sp = Y.size() - lread;
for (int i = 0; i != lread; ++i)
{
block_buffer_output[i] = Y[Sp + i];
}
write(sock, (char*)block_buffer_output, lread * sizeof(double));
}
delete[] block_buffer_input;
delete[] block_input;
delete[] block_buffer_output;
close(sock);
return 0;
}
I want to know why the memcpy() do not work in the 2nd time.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…