problem with blocking sockets in windows c++

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hello,

I have client-server aplications which work with blocking sockets in windows. Here are server and clients sources

Server
<pre class="prettyprint SOCKET server;

UINT MTServerThread(LPVOID pParam)
{
WSADATA wsaData;
sockaddr_in local;
int wsaret=WSAStartup(MAKEWORD(2,2),&wsaData);
if(wsaret!=0)
{
return 0;
}
local.sin_family=AF_INET;
local.sin_addr.s_addr=INADDR_ANY;
local.sin_port=htons((u_short)20248);
server=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(server==INVALID_SOCKET)
{
return 0;
}
if(bind(server,(sockaddr*)&local,sizeof(local))!=0)
{
return 0;
}
int err = listen(server, 256);
if(err!=0)
{
return 0;
}

SOCKET client[MAX_CLIENTS_COUNT];
sockaddr_in from;
int fromlen=sizeof(from);
int clientCount = 0;

while(clientCount < MAX_CLIENTS_COUNT)
{

client[clientCount]=accept(server,
(struct sockaddr*)&from,&fromlen);
AfxBeginThread(ClientThread,(LPVOID)client[clientCount]);
clientCount ++;
}

return 0;
}

UINT ClientThread(LPVOID pParam)
{
int retval;
SOCKET client=(SOCKET)pParam;
int bytesRecv = 0;
int bytesSent;

char receiveBuff[5000];
int ok = 111;
while( bytesRecv != SOCKET_ERROR)
{

bytesRecv = recv( client, receiveBuff, 5000, 0 );
if ( bytesRecv == 0 || bytesRecv == WSAECONNRESET ) {
break;
}

if(bytesRecv != 5000)
AfxMessageBox(L"received bytes are less then 5000");
bytesSent = send( client, (char*)&ok, 4, 0 );
}
return 0;
}
[/code]
<br/>
Client

<pre class="prettyprint int main()
{
const char* servername="localhost";
int retval;

WSADATA wsaData;
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
int wsaret=WSAStartup(0x101,&wsaData);
if(wsaret)
return 0;
SOCKET conn;
conn=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(conn==INVALID_SOCKET)
return 0;
if(inet_addr(servername)==INADDR_NONE)
{
hp=gethostbyname(servername);
}
else
{
addr=inet_addr(servername);
hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
}
if(hp==NULL)
{
closesocket(conn);
return 0;
}
server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server.sin_family=AF_INET;
server.sin_port=htons(20248);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
{
closesocket(conn);
return 0;
}

//----------------------
// Declare and initialize variables.
int bytesSent;
int bytesRecv = SOCKET_ERROR;
int sendbuf[1250];
char recvbuf[4];

for(int i = 0; i < 1250; ++i)
{
sendbuf = i;
}

//----------------------
// Send and receive data.

for(int i = 0; i < 8000; ++i)
{

bytesSent = send( conn, (char*)sendbuf, 5000, 0 );
bytesRecv = recv( conn, recvbuf, 4, 0 );
}

closesocket(conn);
WSACleanup();
return 0;
}[/code]
<br/>
As You see I send 5000 bytes and receive it in server application. But sometimes in server I get less then 5000 and server shows the messagebox.
When I put Sleep(2) befor receiving it works fine. Could you say is there any mistake or not?
Thanks in advance.

View the full article
 
Back
Top