}
//the function can be used to get message form server
//param buf is a char pointer that can store the message which is sent by server
//param n is the maximum length of buf
int Client::receive()
{
if(m_socket == -1)
{
setError(ERROR_SOCKET_CREATE);
return -1;
}
if( recv(m_socket,(char*)&m_recv_datahead,sizeof(DataHead),0) == sizeof(DataHead))
{
int total_length = m_recv_datahead.data_total_length;
if(total_length == 0 )
return 1; //without any data
m_recv_length = total_length;
m_recvbuf = new char[total_length];
int package_length = m_recv_datahead.data_package_length;
int recv_times = total_length/package_length +1;
int i = 1;
int length_left = total_length;
while(i <= recv_times) //three conditions 1. length < packaget 2.length = package*n 3.length > package
{
if(length_left >= package_length) // when the data length is bigger or equril than the package length
{
if(package_length != recv(m_socket, m_recvbuf + (i-1)*package_length ,package_length,0))
{
setError(ERROR_RECV_FAIL);
return -1;
}
}
else
{
if(length_left != 0)
if(length_left != recv(m_socket,m_recvbuf + (i-1)*package_length , length_left,0))
{
setError(ERROR_RECV_FAIL);
return -1;
}
}
length_left = total_length - (i*package_length);
i++;
}
}
else
{
setError(ERROR_RECVHEAD_FAIL);
return -1;
}
return 1;
}
void Client::printerror()
{
}
//
int Client::sendto(char* buf , int n)
{
if(-1 == m_socket )
{
setError(ERROR_SOCKET_CREATE);
return -1;
}
recv函数默认是阻塞的,假如server端用recv接受数据,不用select监控超时,那么假如client永远不发数据,你不是和这个client的连接就永远不会断开?作者: ring8595 时间: 2008-03-14 17:33
谢谢你
但是 select不也要这样吗
for(; {
FD_ZERO(&fdR);
FD_SET(sockfd, &fdR);
switch (select(sockfd + 1, &fdR, NULL, &timeout)) {
case -1:
error handled by u;
case 0:
timeout hanled by u;
default:
if (FD_ISSET(sockfd)) {
now u read or recv something;
/* if sockfd is father and
server socket, u can now
accept() */
}
}
}