\$\begingroup\$
\$\endgroup\$
A small struct
is sent beforehand to the client that specifies package_size
amount of data should be received which is what p->data_value_1
contains.
Server side:
void Server::sendDataSingleUser(char *data_in, int user, unsigned int package_size){
package_size_sent_ = 0;
FD_ZERO(&write_set_);
FD_SET(sockets_[user], &write_set_);
while(package_size_sent_ < package_size){
timeout_.tv_sec = 3;
timeout_.tv_usec = 0;
i_result_ = select(0, 0, &write_set_, 0, &timeout_);
// Socket free, send a package
if(i_result_ > 0){
i_result_ = send(sockets_[num_clients_], data_in+package_size_sent_, package_size - package_size_sent_, 0);
// Move buffer pointer
if(i_result_ > 0){
package_size_sent_ += i_result_;
}
// send error
if(i_result_ == SOCKET_ERROR){
// Handle the error
}
}
// Socket still bussy
else{
// Disconnect the client
}
}
}
Client side:
*size_p = new char[(unsigned int)p->data_value_1];
int temp_count = 0, data_received, package_size = p->data_value_1;
while(temp_count < package_size){
data_received = recv(connect_socket_, size_p+temp_count, package_size - temp_count, 0);
// Move buffer pointer
if(data_received > 0){
temp_count += data_received;
}
}
What can be improved/what's incorrect?
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
In both read and write you should leave the loop after an error (unless you have explicitly tested and fixed the error).
while(totalRecieved < readSize)
{
dataRecieved = recv(socket, date + totalRecieved, readSize - totalRecieved);
if (dataRecieved > 0)
{
totalRecieved += dataRecieved;
continue;
}
if ((dataRecieved == -1) && (errno == EAGAIN || errno == EWOULDBLOCK))
{
// Simple error just try again.
continue;
}
if (dataRecieved == -1 && errno == EINTR)
{
// An interrupt was received.
// This is usually a signal by another thread to give up
// but you can ignore it if you want.
continue;
}
// Any other error is bad.
// looping is just going to cause infinite loops.
break;
}
if (totalRecieved < readSize)
{
// BAD THINGS HAVE HAPPENED
}
answered Jun 10, 2013 at 0:28
-
\$\begingroup\$ Think I got it fixed up in the server part(if an error occurs it closes the clients socket and then calls return. Will add the check to the client part, thanks! \$\endgroup\$David S– David S2013年06月10日 01:03:28 +00:00Commented Jun 10, 2013 at 1:03
lang-cpp