I’m having some strange things happen with my program, and I’m not sure what I should be doing. This is a pseudocode version of what my code looks like so far:
Server:
//Set up Server sockets
int maximum;
// Collect the maximum
cout << "\nEnter a Maximum:";
cin >> maximum;
cout << "\n";
int *array = new int[maximum + 1];
memset(array, 0, sizeof(array));
while(array[0] < anInt){
//receive the array from the client
if(recv(newsockfd, array, maximum, 0) < 0){
perror("ERROR receiving from socket");
}
mathFunction(array); //A function that alters the contents of array
array[0]++;
//If array[0] isn't too big
if(array[0] < anInt){
// Send the array to the client
if(send(newsockfd, array, maximum, 0) < 0){
perror("ERROR sending to socket");
}
}
}
Client:
//Set up Client sockets
//The maximum was already sent over earlier
int *array = new int[maximum + 1];
while(array[0] < anInt){
//receive the array from the server
if(recv(sockfd, array, maximum, 0) < 0){
perror("ERROR receiving from socket");
}
mathFunction(array); //A function that alters the contents of array
array[0]++;
if(send(sockfd, array, maximum, 0) < 0){
perror("ERROR sending to socket");
}
}
My problem is that I keep getting a “Connection reset by peer” error, which leads to a Segmentation Fault, crashing my program. Also, when playing around with the 3rd argument of the send/recv functions (currently set as maximum), my program acts differently. It will actually work perfectly if the user enters a maximum of 100, but anything more than that screws it up.
I know this is a long shot, but can anyone see something that I’m doing wrong?
First of all code that posted by you has a logical error:
Server first receive data from the client, do something with it and then send its result back to the client.
In the other side client also receive data from server, do something with it and then send it back to the server.
And that’s obviously a race condition, no one send data to other side to begin communication.
Beside that logical error you have some C++ errors:
1)
memset(array, 0, sizeof(array))only 0 initializesizeof(int*)bytes from your array not entire array, sincesizeof(array)is alwayssizeof(int*)if you want to 0 initialize entire array (and I think you want it) you should call:or even better:
And in C++ it is much better to use classes like
std::vectorinstead of raw pointers:2) Your array type is
int*andsend/recvcount its input by byte, so if you want tosend/recventire array you must have something like:3) You should check return value of
send/recv, speciallyrecvsince it mayrecvless data in each call, for example you send 8K data andrecvonly receive first 1K and rest of it remain in the network buffer, so you should call it repeatedly until you read your buffer completely.